To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);
Use json_decode() Function to Extract Data From JSON in PHP. We will use the built-in function json_decode() to extract data from JSON. We will convert the JSON string to an object or an array to extract the data. The correct syntax to use this function is as follows.
Parsing JSON with PHPPHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
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:
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.
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
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.
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
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
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'
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:
null
.json_last_error_msg
or put it through something like JSONLint.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.
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.
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
If your JSON is too large for json_decode()
to handle at once things start to get tricky. See:
See: Reference: all basic ways to sort arrays and data in PHP.
You can use json_decode() to convert a json string to a PHP object/array.
Eg.
Input:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
Output:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Few Points to remember:
json_decode
requires the string to be a valid json
else it will return NULL
.json_last_error()
can be used to determine the exact nature of the error.utf8
content, or json_decode
may error out and just return a NULL
value.// Using json as php array
$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';
//or use from file
//$json = file_get_contents('results.json');
$someArray = json_decode($json, true);
foreach ($someArray as $key => $value) {
echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}
We can decode json string into array using json_decode function in php
1) json_decode($json_string) // it returns object
2) json_decode($json_string,true) // it returns array
$json_string = '{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$array = json_decode($json_string,true);
echo $array['type']; //it gives donut
Consider using JSONPath
https://packagist.org/packages/flow/jsonpath
There is a pretty clear explanation of how to use it and parse a JSON-file avoiding all the loops proposed. If you are familiar with XPath
for XML
you will start loving this approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With