JSON array parsing in PHP - php

please help me how to parse following JSON in PHP.
I got following JSON using PIWIK reporting api. How do I get PageTitle from following json in PHP. I tried following code for JSON parsing.
$json = '[
{
"idSite": "1",
"idVisit": "84",
"visitorId": "f08dc1f2a3e1f839",
"visitorType": "returning",
"visitorTypeIcon": "plugins/Live/images/returningVisitor.gif",
"visitConverted": "0",
"visitConvertedIcon": null,
"visitEcommerceStatus": "none",
"visitEcommerceStatusIcon": null,
"searches": "0",
"events": "4",
"actions": "9",
"actionDetails": [
{
"type": "action",
"url": "http://mywwebsiteurl.com",
"pageTitle": "PageTitle",
"pageIdAction": "110"
}
]
}
]';
$visits = json_decode($json, true);
foreach ($visits->actionDetails as $data) {
echo $data->pageTitle;
}
I got following notice
Notice: Trying to get property of non-object
How to get pageTitle from above JSON.

It should be :-
$visits = json_decode($json, true);
foreach ($visits[0]["actionDetails"] as $data) {
echo $data["pageTitle"];
}

You set second attribute to TRUE - so according to the manual.
"When TRUE, returned objects will be converted into associative arrays."
Try using the array aproach
foreach ($visits['actionDetails'] as $data){
echo $data['pageTitle'];
}

As documented in the manual, and mentioned by Matt, the second parameter of json_decode() controls the return type. If it is omitted or set to false (the default) then an object is returned. If it is set to true an array is returned.
Your code, json_decode($json, true);, will return an array but you then try to use the array as an object.

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

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)

Parse json array without value in php

I wonder how to parse a json array without values
Json: {"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}
How can i get the value of email in a foreach loop?
What i mean with "without value" is: there is an array called email and name... How can i get the value for "email" that currently says NOT_UNIQUE?
In your current example, your JSON string is malformed. I dont know if thats a typo on your part while creating your question. Assuming the JSON string is okay in your code, a simple json_decode() will do just fine. Consider this example:
$json_string = '{ "Json": { "status": "FAILED", "errors": { "email": [ "NOT_UNIQUE" ], "name": [ "TOO_SHORT" ] } }}';
$data = json_decode($json_string, true);
echo $data['Json']['errors']['email'][0]; // NOT UNIQUE
use json_decode, json_decode($str, true) will return it as an assosiative array whereas json_decode($str, false) will return objects.
json_decode("{"status":"FAILED","errors":{"email":["NOT_UNIQUE"],"name":["TOO_SHORT"]}}", true)['errors']['email']
should get the email for you.

Get JSON objects in PHP, not array

Im writing a website in php that gets a JSONstring from another php-api Ive created.
The string looks like this:
{
"result": "true",
"results": {
"20": {
"id": "20",
"desc": "a b ct tr",
"active": "1",
"startdate": "2013-04-03",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-03",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
},
"21": {
"id": "21",
"desc": "test",
"active": "0",
"startdate": "2013-04-04",
"starttimehour": "18",
"starttimemin": "0",
"enddate": "2013-04-04",
"endtimehour": "22",
"endtimemin": "0",
"creator": "a"
}
}
}
Ive found lots of answers on how to get information from a JSONarray but Im not using an array here.
So the question is: how can I get the objects that are labeled 20, 21 and so forth(These numbers are generated by the server so I dont know which ones will be returned).
Or should I rewrite how my api returns the JSON as an array instead. Something like this:
{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
// access the number with $key and the associated object with $value
echo 'Number: '.$key;
echo 'Startdate: '.$value['startdate'];
}
I suppose that you are getting the json by POST without any parameter, like
curl http://someapi.somedomain/someresource/ -X POST -d #data.json
so basically
$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);
should solve your problem. and $object will be your json object that you post.
You do get the JSON response as a string. That's just the way JSON works. To "convert" the data to a format and structure that is easily accessible, you can use a PHP function called json_decode().
You have two choices when using the function -
To convert the data into an array. json_decode($jsonString,true)
If you use this method, you would access the data like you would for an associative array. $jsonArray['results']['21']
To convert the data into an object. json_decode($jsonString)
With this method, you would use object notation to traverse the data -
$num = 21;
$jsonObj->results->$num
First you decode the string($string) then you can loop through it and get all the properties of the objects. Remember that accessing properties is with ->prop instead of ['prop']. This way you do not have to deal with it in an array manner.
$jsoned = json_decode($string);
foreach($jsoned->results as $o) {
foreach($o as $key => $value) {
echo "The key is: ".$key." and the value is: ".$value."<br>";
}
}
Working example what will print out:
Key is: id and value is: 20
Key is: desc and value is: a b ct tr
Key is: active and value is: 1
etc...

json_encode, json_decode, array?

I'm trying to get into just data from
{
"data": [{
"media_count": 3045,
"name": "snow",
},
{
"media_count": 79,
"name": "snowman",
},
{
"media_count": 40,
"name": "snowday",
},
{
"media_count": 29,
"name": "snowy",
}]
}
I've been trying, using:
$obj = json_decode($res[0], true);
echo $obj['data']; //this returns an array
I also tried this:
$obj = json_encode($res[0], true);
echo $obj; // this returns json, but not inside `data`
"data": [{
"media_count":54373,
"name":"test"
}]
I just want to get inside data. How would I do so?
Thanks in advance!
UPDATE: Sorry to mention, I would like this in json format please
eventually, I would like to only see
{
"media_count":54373,
"name":"test"
}
Something like thiat
Use json_encode() to get what you want:
$obj = json_decode($res[0], true);
echo json_encode($obj['data']);
In your first example, $obj['data'] returns an array because that's how the JSON is set up. According to the JSON, data is a collection of elements.
To access within the array, you can do this:
foreach($obj['data'] as $object) {
print_r($object);
}
You can also index into it as you want:
print_r($obj['data'][0]);
EDIT
If I'm getting you correct, you want to convert the first JSON to this:
"data": [{
"media_count":54373,
"name":"test"
}]
If so, that is not possible since the second fragment is not valid JSON. (use http://jsonlint.com)
firstly access the data item of the json array;
$obj1=$obj[item];
$sizeobj=sizeof($obj1);
for($i=0;$i<$sizeobj;$i++)
{
// your code to access the data items
// for eg $obj[item][$i][media_count}
}

Categories