Trying to parse JSON with PHP - php

I'm new to php and this has really stumped me - i'm trying to parse this json in order to get the value of match_id.
{
"result": {
"status": 1,
"num_results": 1,
"total_results": 500,
"results_remaining": 499,
"matches": [
{
"match_id": 649218382,
"match_seq_num": 588750904,
"start_time": 1399560988,
"lobby_type": 0,
"players": [
{
"account_id": 4294967295,
"player_slot": 0,
"hero_id": 69
}
]
}
]
}
}
So far I have:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};
But I'm pretty sure that's not the right way to do it at all. All I need out of this JSON file is the match id.

You are getting an array back from json_decode() as you passed the second parameter with a value of true so you access it like any multi-dimensional
array:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
echo $decodedmatchhistory['result']['matches'][0]['match_id'];
Demo
Naturally if you have multiple matches you wish to get the match ID for you can loop through $decodedmatchhistory['result']['matches'] and get them accordingly.

This is your code:
$matchhistoryjson = file_get_contents($apimatchhistoryurl);
$decodedmatchhistory = json_decode($matchhistoryjson, true);
$matchid = $decodedmatchhistory->{'match_id'};
Two issues. First when you set true in a call to json_decode() that returns the results as an array:
When TRUE, returned objects will be converted into associative arrays.
So you would access the data as an array like this:
$matchid = $decodedmatchhistory['match_id'];
But your original syntax is incorrect even if you were accessing the data as an object:
$matchid = $decodedmatchhistory->{'match_id'};
If you set json_decode() to false or even left that parameter out completely, you could do this instead:
$decodedmatchhistory = json_decode($matchhistoryjson);
$matchid = $decodedmatchhistory->match_id;
So try both out & see what happens.

Related

How to correctly parse JSON in PHP

I want to parse values from an Json API, but I cant get it to work
The API returns this JSON:
[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]
I tried to get the ID value like this:
$json_obj = json_decode($resp);
print $json_obj->assets[0]->id;
but I get no result whereas it should be 6. What do I do wrong here?
Remember the outer part of the JSON is an array, as suggested by the opening [. So you need to first access the first (and only) element of it:
$json_obj[0]->assets[0]->id; //<-- note the first [0]
I think the correct answer is
$json_obj = json_decode($resp);
print $json_obj[0]->assets[0]->id;
The json object will be converted to a php array, since you have an array with a object inside in your case it will be a multidimentional array with the objects inside.
Try this its worked for me..
$json ='[
{
"assets": [
{
"id": 6,
"size": 1429504,
"download_count": 1,
"browser_download_url": "https://dl.domain.tld/files/cdbc6e19-cd86-4ed6-8897-37ec5aaee578"
}
]
}
]';
$json_obj = json_decode($json);
var_dump($json_obj[0]->assets[0]->id)
?>
decode JSON to the array and fetch the id by proper array keys
$jToArray = json_decode($resp, TRUE);
echo $jToArray[0]['assets'][0]['id'];//You will get the correct id

json_decode fails with error code 4 when file has two distinct json elements

{
"file": 1,
"format": 1
}
{
"info_sent": 0.0,
"lsd": true,
"send_info": false
}
when the file is arranged like this, json_decode returns a syntax error. this is the configuration file for deluge by the way.
JSON requires a comma between the two elements, and then it should be wrapped as an array.
Like this:
[{
"file": 1,
"format": 1
},
{
"info_sent": 0.0,
"lsd": true,
"send_info": false
}]
To use the original format, create a loop where you decode each element separately and push the resulting object into an array.
Assuming your file has one line per JSON element, your code could look like this:
$result = [];
foreach(file('myfile.txt') as $line) {
$result[] = json_decode($line);
}
If your file is arranged differently (one JSON occupying more than one line), you'll have to change the above code. All depends on the format of the file...

Parsing Multidimensional Nested JSON with PHP

I feel like i am slightly insane, and I have certainly read the docs on this. I am completely unable to echo out various objects in a JSON array in PHP. I am not sure what I'm doing wrong, but I'm ripping my hair out...
Here is my JSON array:
{
"photos": {
"page": 1,
"pages": 1569045,
"perpage": 1,
"total": "1569045",
"photo": [
{
"id": "14842817422",
"owner": "23432140#N06",
"secret": "c37cfa1914",
"server": "3864",
"farm": 4,
"title": "pizza",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0
}
]
},
"stat": "ok"
}
I know this is simple, but I can't get it right. I would like to echo out four different values.
This is what I have been trying:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
$photoSecret = $jsonDecoded['photos']['photo'][0]['secret'];
$photoServer = $jsonDecoded['photos']['photo'][0]['server'];
$photoFarm = $jsonDecoded['photos']['photo'][0]['farm'];
I know this seems newbie. Please help...
Best,
The problem is that you have both objects and arrays in your json, but are using array syntax in your php.
There are two ways to fix this, 1st simply set the second parameter of json_decode to true:
json_decode($json, true);
This will create a multidimentional array you can access as suggested in your question, eg:
$photoId = $jsonDecoded['photos']['photo'][0]['id'];
Alertinitivly you can use object property syntax on your existing $jsonDecoded:
$photoId = $jsonDecoded->photos->photo[0]->id;
if there are multiple photo sub arrays then you can do like this.
//this will create array instead of object
$jsonDecoded = json_decode($your_feed_data,true);
foreach($jsonDecoded['photos']['photo'] as $sub_array){
$photoId = $sub_array['id'];
$photoSecret = $sub_array['secret'];
$photoServer = $sub_array['server'];
$photoFarm = $sub_array['farm'];
}

Notice: Trying to get property of non-object - maybe string?

I would like to get the value of "Records"
When is try this code:
$json = file_get_contents('URL');
var_dump($json);
This is the result:
string(25289) "{ "ProductsSummary": { "Records": 10, "TotalRecords": 2874, "TotalPages": 288, "CurrentPage": 1 }, "Products": [ { "...
When I try this code
$json = file_get_contents('URL');
$obj = json_decode($json);
echo $obj;
echo $obj->{'ProductsSummary'}->{'Records'};
echo $obj->ProductsSummary->Records;
echo $obj[0]->ProductsSummary->Records;
echo $obj->ProductsSummary[0]->Records;
echo $obj->ProductsSummary[1];
The Output is:
{ "ProductsSummary": { "Records": 10, "TotalRecords": 2879, "TotalPages": 288, "CurrentPage": 1 }, "Products": [ { "Last.... }
Notice: Trying to get property of non-object in ...
Notice: Trying to get property of non-object in ...
Notice: Trying to get property of non-object in ...
Since you do not have valid JSON, I'm pretty sure that json_decode() is just failing. As per the manual:
Returns the value encoded in json in appropriate PHP type. Values
true, false and null are returned as TRUE, FALSE and NULL
respectively. NULL is returned if the json cannot be decoded or if the
encoded data is deeper than the recursion limit.
You can verify that with e.g. the is_null() function:
$obj = json_decode($json);
if( is_null($obj) ){
// Invalid JSON, don't need to keep on working on it
}else{
// Read data
}
... although the proper way would be to explicitly check for errors with json_last_error(), which should equal JSON_ERROR_NONE unless something went wrong.
If everything works fine, $obj will be an object, thus feeding echo with it will never yield anything useful:
echo $obj;
You might want to use var_dump() instead.
$json is a string. You should decode it first using json_decode($json)

How to create a JSON array in php?

I am trying to create a simple android application that takes data from a database and displays it in a list format on the android screen. I made a php script that queries the database and returns a json object. I convert the json object into json array and extract the relevant data for display. But I am getting this error "JSONException: type org.json.JSONObject cannot be converted to JSONArray".
Following is my php script -
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$username = $_POST['username'];
$events = $db->viewAttendingEvent($username);
if ($events) {
$response["success"] = 1;
$response["event"]["owner"] = $events["owner"];
$response["event"]["friendsnames"] = $events["friendsnames"];
$response["event"]["vote"] = $events["vote"];
$response["event"]["accepted"] = $events["accepted"];
$response["event"]["eventname"] = $events["eventname"];
$response["event"]["eventnumber"] = $events["eventnumber"];
$response["event"]["created_at"] = $events["created_at"];
echo json_encode($response);
This is the json which I receive back :
{
"tag": "view_invitations",
"success": 1,
"error": 0,
"event": {
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-29 22:27:31.843528"
}
}
I am trying to extract 'event' from this json object, which is not an array.
it should be
{
"event": [
{
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-2922: 27: 31.843528"
}
]
}
Can someone help me how to make this a valid jsonArray ? Thanks
If you're looking to get a JavaScript 'Array' (from which I mean an Object with nothing but integer keys) then you need to only have integer keys in your PHP Array.
This article is a pretty good resource and explains some of the differences between arrays and objects in javascript. The relevant quote here comes from the What Arrays Are section (emphasis mine):
Javascript arrays are a type of object used for storing multiple
values in a single variable. Each value gets numeric index and may be
any data type.
No it should not be what you proposed it should be. If that were the case you would have to have your php be this:
$response["event"][0]["owner"] = $events["owner"];
$response["event"][0]["friendsnames"] = $events["friendsnames"];
$response["event"][0]["vote"] = $events["vote"];
$response["event"][0]["accepted"] = $events["accepted"];
$response["event"][0]["eventname"] = $events["eventname"];
$response["event"][0]["eventnumber"] = $events["eventnumber"];
$response["event"][0]["created_at"] = $events["created_at"];
The way you have it now is event is an associative array so it converts it to an object. You are expecting that event = an array of objects. So you need to either change your php code to make event be an array of objects (as demonstrated above) or you need to modify your expectations to have event = an object.

Categories