How to extract and access data from JSON with PHP?
Intro
First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode()
.
$data = json_decode($json);
Therein you might find:
- scalars: strings, ints, floats, and bools
- nulls (a special type of its own)
- compound types: objects and arrays.
These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.
There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.
Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.
Accessing object properties
You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property
.
$json = '
{
"type": "donut",
"name": "Cake"
}';
$yummy = json_decode($json);
echo $yummy->type; //donut
Accessing array elements
You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0]
.
$json = '
[
"Glazed",
"Chocolate with Sprinkles",
"Maple"
]';
$toppings = json_decode($json);
echo $toppings[1]; //Chocolate with Sprinkles
Iterate over it with foreach
.
foreach ($toppings as $topping) {
echo $topping, "\n";
}
Glazed
Chocolate with Sprinkles
Maple
Or mess about with any of the bazillion built-in array functions.
Accessing nested items
The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc
.
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$yummy = json_decode($json);
echo $yummy->toppings[2]->id; //5004
Passing true
as the second argument to json_decode()
When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key']
.
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$yummy = json_decode($json, true);
echo $yummy['toppings'][2]['type']; //Maple
Accessing associative array items
When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value)
syntax, eg
$json = '
{
"foo": "foo value",
"bar": "bar value",
"baz": "baz value"
}';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
echo "The value of key '$key' is '$value'", PHP_EOL;
}
Prints
The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'
Don't know how the data is structured
Read the documentation for whatever it is you're getting the JSON from.
Look at the JSON - where you see curly brackets {}
expect an object, where you see square brackets []
expect an array.
Hit the decoded data with a print_r()
:
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$yummy = json_decode($json);
print_r($yummy);
and check the output:
stdClass Object
(
[type] => donut
[name] => Cake
[toppings] => Array
(
[0] => stdClass Object
(
[id] => 5002
[type] => Glazed
)
[1] => stdClass Object
(
[id] => 5006
[type] => Chocolate with Sprinkles
)
[2] => stdClass Object
(
[id] => 5004
[type] => Maple
)
)
)
It'll tell you where you have objects, where you have arrays, along with the names and values of their members.
If you can only get so far into it before you get lost - go that far and hit that with print_r()
:
print_r($yummy->toppings[0]);
stdClass Object
(
[id] => 5002
[type] => Glazed
)
Take a look at it in this handy interactive JSON explorer.
Break the problem down into pieces that are easier to wrap your head around.
json_decode()
returns null
This happens because either:
- The JSON consists entirely of just that,
null
. - The JSON is invalid - check the result of
json_last_error_msg
or put it through something like JSONLint. - It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to
json_decode()
.
If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.
Object property name contains a special character
Sometimes you'll have an object property name that contains something like a hyphen -
or at sign @
which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.
$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);
echo $thing->{'@attributes'}->answer; //42
If you have an integer as property see: How to access object properties with names like integers? as reference.
Someone put JSON in your JSON
It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.
$json = '
{
"type": "donut",
"name": "Cake",
"toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';
$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);
echo $toppings[0]->type; //Glazed
Data doesn't fit in memory
If your JSON is too large for json_decode()
to handle at once things start to get tricky. See:
- Processing large JSON files in PHP
- How to properly iterate through a big json file
How to sort it
See: Reference: all basic ways to sort arrays and data in PHP.
Get value from JSON array in PHP
First you have to decode your json data
$json = json_decode($data[0]['json']);
Then you can access your AfterParticipationHeader
$json->Canvas[0]->MainObjects->{"After Participation"}->afterParticipationHeader
get data from json array in php
The results
key is a true array, not an unordered map (key/value). Additionally, you should be accessing the decoded $data
, not the $json
string.
This should work for you:
$test = $data['model']['results'][0]['balance'];
This is what should have tipped you off:
{"results":[{"message"
^ ^
| |
| \-- Start of an array
|
\-- Start of an object
Get values from JSON array in PHP with the following format?
First of all you have not a json-structure inside the "data"
field, but just a string, which contains json data.
Therefore you did it wrong, when convert the data into a constant value. You have to double all backslashes first.
Then you can get the "data"
element and perform json_decode
once more.
<?php
$s = '[
{
"data": "[{\\"name\\":\\"step 1 kdfhghdkgjdf\\\\nkjdhfgkjhdkjghd\\\\nkdfjhgkjdhfg\\\\n\\\\n\\\\ndfjhgkjdfjhgdfgd\\\\n\\"},{\\"name\\":\\"step 2 dhfgkjdfhkhkjchjkfd\\\\ndkjhjdf\\\\njhkdfhkghdkfhgkdhg\\\\n\\\\n\\\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\\"},{\\"name\\":\\"step 3 kkkkkkkkkk\\"},{\\"name\\":\\"step 4 ljlejrhlflhgf\\\\n\\\\n\\\\ndfhjk\\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
$data = json_decode($obj[0]['data'], true);
foreach($data as $item) {
print($item['name'] . "\r\n");
}
PHP JSON Array Get Value
You are missing the ['data']
key,
<?php
$json = '{"status":200,"response_msec":15,"data":{"android":{"test1":15,"test2":6,"test3":15,"test4":101,"test5":87,"test6":8,"test9":119,"test10":101,"test11":107}}}';
$array = json_decode($json, true);
var_dump(array_keys($array['data']['android']));
Check here i have made a php sandbox http://sandbox.onlinephpfunctions.com/code/6f97a9bb499b54919b40d4d12f49049fdd732aef
Also, You can use the function array_keys()
to get only the keys of an array, that's what i did.
How to extract data from a json array with php?
First problem the json is not valid. There are few issue. You can validate at following website: http://jsonlint.com/
And the json have two full name. So following code will help to extract those two full names.
$json = 'Assign the json here';
$json_array = json_decode($json);
echo $json_array->result->places[0]->contained_within[0]->full_name;
echo $json_array->result->places[0]->full_name;
- Assign the valid json to the variable
$json
within single quot (') as json have double quot.
The tested code available here: http://sugunan.net/demo/json1.php
If we take your foreach example it need to be modified like follows. But that is not tested answer.
foreach ($data['places'] as $item) {
echo $item->contained_within[0]->full_name;
echo $item->full_name;
}
Following is the validated json of the above. Which had few unnecessary ",". And it missed few brackets.
{
"query": {
"params": {
"accuracy": 0,
"coordinates": {
"coordinates": [
-122.42284884,
37.76893497
],
"type": "Point"
},
"granularity": "neighborhood"
},
"type": "reverse_geocode"
},
"result": {
"places": [
{
"attributes": {},
"bounding_box": {
"coordinates": [
[
[
-122.42676492,
37.75983003
],
[
-122.420736,
37.75983003
],
[
-122.420736,
37.77226299
],
[
-122.42676492,
37.77226299
]
]
],
"type": "Polygon"
},
"contained_within": [
{
"attributes": {},
"bounding_box": {
"coordinates": [
[
[
-122.51368188,
37.70813196
],
[
-122.35845384,
37.70813196
],
[
-122.35845384,
37.83245301
],
[
-122.51368188,
37.83245301
]
]
],
"type": "Polygon"
},
"country": "United States",
"country_code": "US",
"full_name": "San Francisco, CA",
"id": "5a110d312052166f",
"name": "San Francisco",
"place_type": "city"
}
],
"country": "United States",
"country_code": "US",
"full_name": "Mission Dolores, San Francisco",
"id": "cf7afb4ee6011bca",
"name": "Mission Dolores",
"place_type": "neighborhood"
}
]
}
}
Get values from JSON array using PHP
You no need to encode your incoming $_POST
data.
Just say:
echo $_POST['First_Name'];
If you get a json
data, decode it into an array:
$data = '{"First_Name":"Fred"}';
$decoded = json_decode($data, true);
echo $decoded['First_name'];
Related Topics
How to Fetch Associative Array Grouped by the Values of a Specified Column with Pdo
Is My Understanding of PHP Sessions Correct
Set an Environment Variable in .Htaccess and Retrieve It in PHP
Curl and Ping - How to Check Whether a Website Is Either Up or Down
Curl and Https, "Cannot Resolve Host"
Setcookie() Does Not Set Cookie in Google Chrome
Access a File Which Is Located Before/Outside the Server Root Directory
Can You Append Strings to Variables in PHP
Many Hash Iterations: Append Salt Every Time
Access Denied for User 'Root'@'Localhost' with PHPmyadmin
Php's JSON_Encode Does Not Escape All JSON Control Characters
PHP Fatal Error: Call to Undefined Function MySQLi_Stmt_Get_Result()
How to Set, Get and Destroy Cookies in Wordpress
A Yaml File Cannot Contain Tabs as Indentation
How to Get the Unicode Value of a Character or Vise Versa with PHP
Using If(Isset($_Post['Submit'])) to Not Display Echo When Script Is Open Is Not Working