PHP - JSON returning null with different objects - php

I have two different set of json object as follows.
'{
"eventos": [
{"Event":"QueueParams","Queue":"755","Max":"0","Strategy":"fewestcalls","Calls":"0","Holdtime":"19","TalkTime":"491","Completed":"89","Abandoned":"4","ServiceLevel":"0","ServicelevelPerf":"0.0","Weight":"0","ActionID":"4152750549"},
{"Event":"QueueMember","Queue":"755","Name":"PJSIP/428","Max":"","Location":"PJSIP/428","StateInterface":"PJSIP/428","Membership":"dynamic","Penalty":"0","CallsTaken":"2","LastCall":"1607350581","Status":"2","Paused":"0","ActionID":"4152750549"},
]
}';
$response = json_decode($response);
dd($response);
The problem is, it returns null output.
I want to get json result displayed with different objects. What changes are needed here so that I can display output of different objects ?

Your JSON have a syntax error. Just remove the comma right after the last { ActionID":"4152750549"},.
It have to be like this:
'{
"eventos": [
{"Event":"QueueParams","Queue":"755","Max":"0","Strategy":"fewestcalls","Calls":"0","Holdtime":"19","TalkTime":"491","Completed":"89","Abandoned":"4","ServiceLevel":"0","ServicelevelPerf":"0.0","Weight":"0","ActionID":"4152750549"},
{"Event":"QueueMember","Queue":"755","Name":"PJSIP/428","Max":"","Location":"PJSIP/428","StateInterface":"PJSIP/428","Membership":"dynamic","Penalty":"0","CallsTaken":"2","LastCall":"1607350581","Status":"2","Paused":"0","ActionID":"4152750549"}
]
}';
For any Json problem, run a json_last_error() right after the decode.

For example, to show each ActionID;
<?php
$rawJson = '{"eventos": [{"Event":"QueueParams","Queue":"755","Max":"0","Strategy":"fewestcalls","Calls":"0","Holdtime":"19","TalkTime":"491","Completed":"89","Abandoned":"4","ServiceLevel":"0","ServicelevelPerf":"0.0","Weight":"0","ActionID":"4152750549"}, {"Event":"QueueMember","Queue":"755","Name":"PJSIP/428","Max":"","Location":"PJSIP/428","StateInterface":"PJSIP/428","Membership":"dynamic","Penalty":"0","CallsTaken":"2","LastCall":"1607350581","Status":"2","Paused":"0","ActionID":"4152750549"} ] }';
$json = json_decode($rawJson);
$eventos = $json->eventos;
foreach ($eventos as $event) {
echo $event->ActionID . PHP_EOL;
}
Note: There was an trailing comma (,) behind the last event object, I've removed it to make it valid JSON.
Try it online!

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 decoded value type show as array instead of object

I have below json data and decode it to display on the screen. When I check the type of the value, it shows array instead of object. How to get actual type of value in PHP.
JSON is
{ "allData" : { "image" : [], "contents": {.., "box": {}, "text":[]} } }
When I decode and parse the above JSON data the "allData", "contents", "box" type are shows as array instead of object. How can I get those type as object and "image" type as array. Please help.
Thanks,
Guru
This normally occurs when you are using the true option in the json_decode function.
For eg.,
$str = '{"allData":{"image":["img1.png"],"contents":{"title":"title name","box":{"name":["sample text 1","sample text2"]},"text":[]}}}';
var_dump(json_decode($str, true));
Just try to remove the true in the json_decode function and you should get an object.
Hope this helps.
If you use json_decode with the true option, it will return the result as an array.
Maybe you can check this link.
If you get "Cannot use object of type stdClass as array" the error, you can look at this answer.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Extract from the RFC 7159 (JSON) :
These are the six structural characters:
begin-array = ws %x5B ws ; [ left square bracket
begin-object = ws %x7B ws ; { left curly bracket
end-array = ws %x5D ws ; ] right square bracket
end-object = ws %x7D ws ; } right curly bracket
..
However: php allows you to treat the result as an array (of arrays)
so:
json_decode($json, true); // return as array
returns the result as an array.
and
json_decode($json)
gives you the result as Objects AND arrays . So given your example:
"allData" : { "image" : [], ..
returns a stdClass-Object with the field "image" of type array. The array is empty for your example.
So to retrieve all images, use something like:
$result=json_decode($json);
foreach($result->allData->image as $img) {
echo "found image: $img.";
}

Change API Response to an array in PHP

I have an API which is returning me response like this.
{
"logs": [
[
"2018-05-22 00:10:16",
"Billed"
]
],
"package": "superpremium",
"subdate": "2018-05-08 14:18:18",
"submedium": "CALL"
}
I'm trying to change into array so It can be easily accessible for me. For example.
$response['subdate']; // echo 2018-05-08 14:18:18
$response['submedium']; // echo CALL
$response['package']; // echo superpremium
and the logs one should be like
$response['logs'];
logs must be an array so I can use foreach log to display all values of an array like 2018-05-22 00:10:16 or "Billed" etc
I have used below codes but returns empty screen.
json_decode($response, true);
json_decode($response);
I'm trying to change into array
Just cast it into one then:
$response = (array) json_decode($response);
After that, you can easily access $response['subdate'] etc.
Use json_decode($your_response) method. Your json data will get converted to arrays.
Like:
$response = json_decode($api_response);
And then you can access the values as (By seeing your data, seems that you are getting object):
$subdate = $response->subdate; // echo 2018-05-08 14:18:18
$submedium = $response->submedium; // echo CALL
$package = $response->package;
$json_data = json_decode($YourJSONResponse, true);
Then these will be available:
$json_data["package"]
$json_data["subdate"]
$json_data["submedium"]
Please change date from:
"submedium": "CALL",
To:
"submedium": "CALL"
Remove char "," and used function json_decode it, and enjoy

Json decode returns null value

i know this question ask many time before but still i could't get this working.
i have a json and when i dump $TenentsAccessible output is this
string(71) "[{`TenantID`:`test.com`,`Name`:`12thdoor`}]"
i need to get the value inside TenantID property. so i use json decode to convert this to php array but is returns null
$jnTenant = json_decode($TenentsAccessible,TRUE);
$tenantID = $jnTenant["TenantID"];
var_dump($jnTenant); // this return null
i try to remove the &quot and unwanted characters using this
$TenentsAccessible = str_replace('"', '"', $TenentsAccessible);
$TenentsAccessible=preg_replace('/\s+/', '',$TenentsAccessible);
i know this type of question ask before but i still could't get this to work. appropriate the hlep. thanks
you can check your json code on JsonLint.
I tried your code and it's not correct because of backticks (`).
So you should replace with (") to have
[{
"TenantID": "test.com",
"Name": "12thdoor"
}]
As hasan described in his answer, json_decode returns a multi-dimensional array, so to get TenantID:
$jnTenant = json_decode('[{"TenantID":"test.com","Name":"12thdoor"}]',true);
$tenantID = $jnTenant[0]['TenantID'];
var_dump($tenantID) ;
If you want to get the "TenantID" in the way you described, you have to modify (if you can) the json like this
{
"TenantID": "test.com",
"Name": "12thdoor"
}
Hope it helps.
try it :
$jnTenant = json_decode('[{"TenantID":"test.com","Name":"12thdoor"}]',true);
$tenantID = $jnTenant[0]['TenantID'];
var_dump($tenantID) ;
correct json and corect get json !
for understand this plz print_r( $jnTenant );
this varibale is Two-dimensional array .

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.

Categories