Accessing value inside multi-dimension JSON array using PHP - php

I read several posts on here and have been unable to find success in resolving the problem I am having.
I am trying to figure out how to get the NAME field from the UploadImage array.
I have the following JSON being passed to me from a Webhook.
{
"$version":5,
"Entry":{
"Number":"11",
"Order":null,
"Origin":
{
"City":"Portland",
"CountryCode":"US",
}
,
"Message":"the message",
"UploadImage":[
{
"ContentType":"image/png",
"Id":"F-lMbiCYdwiYS8ppkQS4gsyE",
"Name":"Screen.png",
"Size":55907
}
],
"Subject":"here is the subject"
}
I have no problem grabbing the value of Subject or Message, but I cannot figure out how to grab the NAME within UploadImage.
$contact = json_decode($json);
$subject=$contact->{'Subject'};
When I do
$uploadimage=$contact->{'UploadImage'};
it just writes out ARRAY.
I can do
echo $contact->{'Entry'}->{'Number'};
and it works, so it has to be something with the bracket being there before the curly bracket. I know this has to be something simple that I am missing.
Any help is GREATLY appreciated.

$uploadimage=$contact->{'UploadImage'}[0]->{'Name'};

Firstly try
$contact = json_decode($json, true);
Adding the second argument returns an array instead of an object which will make things easier. Objects with numerical keys are troublesome... Now you can,
print_r($contact);
to see exactly what you've got. I imagine that
echo $contact['UploadImage'][0]['Name'];
Will get you what you're looking for.
Notice that UploadImage contains an array of objects (or an array of arrays after conversion).

another solution is:
$contact = json_decode($text);
$name = '';
foreach($contact->UploadImage as $k=>$v){
foreach($v as $k2=>$v2){
echo $k2.' - '.$v2.'<br />';
if($k2=='Name'){ $name = $v2;}
}
};
var_dump($name);
//response
ContentType - image/png
Id - F-lMbiCYdwiYS8ppkQS4gsyE
Name - Screen.png
Size - 55907
//name
string 'Screen.png' (length=10)

Have you try to use like below:
$uploadimage=$contact->UploadImage[0]->Name;

In JSON the square braces [] mark an array section and the curly braces {} mark an object. In your JSON string UploadImage is an array, which contains a single object.

Try changing your JSON as follows:
{
"$version": 5,
"Entry": {
"Number": "11",
"Order": null,
"Origin": {
"City": "Portland",
"CountryCode": "US"
},
"Message": "the message",
"UploadImage": {
"ContentType": "image/png",
"Id": "F-lMbiCYdwiYS8ppkQS4gsyE",
"Name": "Screen.png",
"Size": 55907
},
"Subject": "here is the subject"
}
}

Related

JSON Parsing Error: Warning: Attempt to read property on array

am trying to parse this JSON from a Football API using PHP.
Below is a subset of the JSON output.
Specifically, I am trying to retrieve the “45%” value from the "home" element from the below json.
$json = '{
"get": "predictions",
"parameters": {
"fixture": "198772"
},
"errors": [],
"results": 1,
"paging": {
"current": 1,
"total": 1
},
"response": [{
"predictions": {
"winner": {
"id": 1189,
"name": "Deportivo Santani",
"comment": "Win or draw"
},
"win_or_draw": true,
"under_over": "-3.5",
"goals": {
"home": "-2.5",
"away": "-1.5"
},
"advice": "Combo Double chance : Deportivo Santani or draw and -3.5 goals",
"percent": {
"home": "45%",
"draw": "45%",
"away": "10%"
}
}
}]
}';
I have tried the following codes but it does not work
$response = json_decode($json);
echo 'Output: '. $response->response->predictions->percent->home;
The error i am getting is:
Warning: Attempt to read property "predictions" on array in C:\xampp\htdocs\xampp\livescore\api-test\predictions.php on line 93
I also tried this but no luck.
echo 'Output: '. $response->response[0]->predictions[0]->percent[0]->home;
appreciate any help or insights I can get.
thanks in advance.
Whenever you see a [ in a json (or any other) object, it's the start of an array, and to reach a child of that array you have to reference it's index (postition). For what you want, this would do it.
$response = json_decode($json);
echo 'Output: '. $response->response[0]->predictions->percent->home;
"response": [{ shows the beginning of an array, and since there's only one item in the array (starting with {) you can reference it by it's index 0. If there were many items in the array, you could loop over them, like
$response->response.forEach(arrayItem => {
// arrayItem is the current element in the array you're looping though
})
You've probably missed that only value of "response" is an array, which has dictionary inside.
Try this: $response->response[0]->predictions->percent->home

PHP Only Returning Last JSON Object

I'm attempting to do something I've done many times before (access objects in a JSON file with PHP) and for some reason json_decode is only returning the last item in the JSON array. Here's the JSON:
{
"person": {
"lname": "smith",
"fname": "bob"
},
"person": {
"lname": "jones",
"fname": "jane"
}
}
And the PHP:
<?php
//access and dump
$json = file_get_contents('people.json');
$filey = json_decode($json, true);
var_dump($filey);
?>
The result is only the last item in the array:
array (size=1)
'person' =>
array (size=2)
'lname' => string 'jones' (length=5)
'fname' => string 'jane' (length=4)
Using json_last_error returns no errors and I'm valid according to jsonlint. I'm also not finding any console errors when I load the page.
I'm totally stumped and can't see anything different from the times I've done this before - can anyone identify what I'm missing here?
That's because your json object names "person" within json array are similar so json decode will override the values with latest.
Consider something like
{
"person1": {
"lname": "smith",
"fname": "bob"
},
"person2": {
"lname": "jones",
"fname": "jane"
}
}
and your code will work fine.
Marcatectura, I know you've already accepted the answer that suggests using different object keys but I thought you should know. If you want an array in PHP, You don't even need object names. The following JSON will do:
[
{
"lname": "Dawes",
"fname": "April"
},
{
"lname": "Colin",
"fname": "Dick"
}
]
A trick I use when I'm designing my JSON is to build a sample PHP array in the shape I want json_decode to give me, encode that array and output the result to screen. So what I posted above is the result of:
$arr = [
['lname'=>'Dawes','fname'=>'April'],['lname'=>'Colin','fname'=>'Dick'],
];
$json = json_encode($arr);
echo $json;
Since I built a JSON by encoding an array having the shape I want, I can be confident that even as my data change, json_decode($json,true) will give me the array shape I expect.
Happy coding.
When you use json_decode(true), your json is now an array.
You cannot have two array keys that are the same, in this case "person".
If you still want to use json_decode(true), then change "person" to "person1" or so.
Try both var_dump($filey) and var_dump($json), you will see what I'm talking about.

extracting json in php

From MySQL row, I have this json formatted data:
$row['details'] =
{
"previous_employer":[
{"employer":"string1","address":"address1"},
{"employer":"string2","address":"address2"},
{"employer":"string3","address":"address3"}],
"profile":[
"firstname":"John",
"lastname":"Adams",
"gender":"male",
"age":"35",
"contact":"123456789"]
}
I want to extract employer and address on the previous_employer array of objects,
but when I do this:
$json = json_decode($row['details'],true); //decode into array
foreach($json['previous_employer'] as $d){
echo "employer:".$d['employer']."<br>address:". $d['address']."<br>";
}
it gives me an error of
Warning: Invalid argument supplied for foreach()
How can I fix this? Pls advise.. thanks!
You JSON is invalid, "profile" must be
An Object:
"profile": {
"firstname": "John",
"lastname": "Adams",
"gender": "male",
"age": "35",
"contact": "123456789"
}
or an Array of Object (here his length == 1)
"profile": [{
"John",
"Adams",
"male",
"35",
"123456789"
}]
or a Simple Array (not associative array/map)
"profile": [
"John",
"Adams",
"male",
"35",
"123456789"
]
Now, your posted code will work as a charm without any modifications ... :)
json_decode() does not necessarily succeed (just imagine you feed it with complete garbage, why should it return something?). You need to do the following error checking:
Verify its return value:
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.
If valid data can be expected to return null some times, call json_last_error() and check whether it's JSON_ERROR_NONE.
Last but not least, you can explore any variable with var_dump(). You don't need to make assumptions about its content.

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.

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