json_decode PHP

Introduction

Let us look at handling JSON with PHP

Simplest JSON

Suppose we have the following JSON

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'

Run json_decode() without extra parameters

var_dump(json_decode($json));

object(stdClass)#4 (5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) }

In this case json_decode() returns object

Now run json_decode() with the true argument

var_dump(json_decode($json, true));

array(5) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> int(3) ["d"]=> int(4) ["e"]=> int(5) }

Now we got array

Note that in the first case (no arguments) var_dump returns an object, and in the second (true argument) an array

Read more about printing array contents here

$json_decode = json_decode($json); $json_decode_true = json_decode($json,true); $arraydata = implode(',' , $json_decode_true); echo $arraydata;

1,2,3,4,5

Try pulling individual elements from the array

echo $json_decode_true["a"]; echo'<br>; echo $json_decode_true["b"];

1
4

JSON with nesting

Make it harder. Let the JSON now contain second-level nestings.

$json2 = ' { "a": {"a_item_1": 11, "a_item_2": 12, "a_item_3": 13}, "b": 2, "c": 3, "d": {"d_item_1": 41, "d_item_2": 42, "d_item_3": 43}, "e": 5 }' ;

Try getting one nested element.

Plain elements (b, c, e) can be printed with echo; for elements that are arrays themselves (a, d) use for example implode(), details here

$json_decode_true2 = json_decode($json2, true); echo $json_decode_true2["c"]; echo'<br>; $d = $json_decode_true2["d"]; $dvalue = implode( , $d); echo $dvalue; echo'<br>; echo $json_decode_true2["d"]["d_item_2"];

3
41,42,43
42

As you can see, plain elements are still available. New elements return Array when addressing the top level, or a value when addressing an array element.

JSON with an array

Arrays sit in square brackets. Suppose it is quite simple.

{ "a": [{ "a_item_1": 11, "a_item_2": 12, "a_item_3": 13 }, { "a_item_4": 14, "a_item_5": 15, "a_item_6": 16 } ], "b": 2, "c": 3, "d": { "d_item_1": 41, "d_item_2": 42, "d_item_3": 43 }, "e": 5 }

To address an array element first specify its index in square brackets.

Get the elements a_item_3 and a_item_6 , note that they sit in different parts of the nested array a

Expect 13 and 16

$json_decode_true3 = json_decode($json3, true); echo $json_decode_true3["a"][0]["a_item_3"]; echo <br>; echo $json_decode_true3["a"][1]["a_item_6"];

13
16

Banner image

Real example

You can study a real-API example in the article «Handling a real API request response»

Article author: Andrei Olegovich