How do I extract data from JSON with PHP? -




this intended general reference question , answer covering many of never-ending "how access data in json?" questions. here handle broad basics of decoding json in php , accessing results.

i have json:

{     "type": "donut",     "name": "cake",     "toppings": [         { "id": "5002", "type": "glazed" },         { "id": "5006", "type": "chocolate sprinkles" },         { "id": "5004", "type": "maple" }     ] } 

how decode in php , access resulting data?

intro

first off have string. json not array, object, or data structure. json text-based serialization format - fancy string, still string. decode in php using json_decode().

 $data = json_decode($json); 

therein might find:

these things can encoded in json. or more accurately, these php's versions of things can encoded in json.

there's nothing special them. not "json objects" or "json arrays." you've decoded json - have basic everyday php types.

objects instances of stdclass, built-in class generic thing that's not important here.


accessing object properties

you access properties of 1 of these objects same way public non-static properties of other object, e.g. $object->property.

$json = ' {     "type": "donut",     "name": "cake" }';  $yummy = json_decode($json);  echo $yummy->type; //donut 

accessing array elements

you access elements of 1 of these arrays same way other array, e.g. $array[0].

$json = ' [     "glazed",     "chocolate sprinkles",     "maple" ]';  $toppings = json_decode($json);  echo $toppings[1]; //chocolate sprinkles 

iterate on foreach.

foreach ($toppings $topping) {     echo $topping, "\n"; } 

glazed
chocolate sprinkles
maple

or mess of bazillion built-in array functions.


accessing nested items

the properties of objects , elements of arrays might more objects and/or arrays - can continue access properties , members usual, e.g. $object->array[0]->etc.

$json = ' {     "type": "donut",     "name": "cake",     "toppings": [         { "id": "5002", "type": "glazed" },         { "id": "5006", "type": "chocolate sprinkles" },         { "id": "5004", "type": "maple" }     ] }';  $yummy = json_decode($json);  echo $yummy->toppings[2]->id; //5004 

passing true second argument json_decode()

when this, instead of objects you'll associative arrays - arrays strings keys. again access elements thereof usual, e.g. $array['key'].

$json = ' {     "type": "donut",     "name": "cake",     "toppings": [         { "id": "5002", "type": "glazed" },         { "id": "5006", "type": "chocolate sprinkles" },         { "id": "5004", "type": "maple" }     ] }';  $yummy = json_decode($json, true);  echo $yummy['toppings'][2]['type']; //maple 

don't know how data structured

read documentation whatever you're getting json from.

look @ json - see curly brackets {} expect object, see square brackets [] expect array.

hit decoded data print_r():

$json = ' {     "type": "donut",     "name": "cake",     "toppings": [         { "id": "5002", "type": "glazed" },         { "id": "5006", "type": "chocolate sprinkles" },         { "id": "5004", "type": "maple" }     ] }';  $yummy = json_decode($json);  print_r($yummy); 

and check output:

stdclass object (     [type] => donut     [name] => cake     [toppings] => array         (             [0] => stdclass object                 (                     [id] => 5002                     [type] => glazed                 )              [1] => stdclass object                 (                     [id] => 5006                     [type] => chocolate sprinkles                 )              [2] => stdclass object                 (                     [id] => 5004                     [type] => maple                 )          )  ) 

it'll tell have objects, have arrays, along names , values of members.

if can far before lost - go far , hit that print_r():

print_r($yummy->toppings[0]); 
stdclass object (     [id] => 5002     [type] => glazed ) 

take @ in this handy interactive json explorer.

break problem down pieces easier wrap head around.


json_decode() returns null

this happens because either:

  1. the json consists entirely of that, null.
  2. the json invalid - check result of json_last_error_msg or put through jsonlint.
  3. it contains elements nested more 512 levels deep. default max depth can overridden passing integer third argument json_decode().

if need change max depth you're solving wrong problem. find out why you're getting such nested data (e.g. service you're querying that's generating json has bug) , not happen.


object property name contains special character

sometimes you'll have object property name contains hyphen - or @ sign @ can't used in literal identifier. instead can use string literal within curly braces address it.

$json = '{"@attributes":{"answer":42}}'; $thing = json_decode($json);  echo $thing->{'@attributes'}->answer; //42 

if have integer property see: how access object properties names integers? reference.


someone put json in json

it's ridiculous happens - there's json encoded string within json. decode, access string usual, decode that, , 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 json large json_decode() handle @ once things start tricky. see:


how sort it

see: reference: basic ways sort arrays , data in php.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -