Home » Php » json – PHP json_decode depth parameter doesn't work

json – PHP json_decode depth parameter doesn't work

Posted by: admin July 12, 2020 Leave a comment

Questions:

PHP’s json_decode function has a “depth” parameter, where you can specify how deep it will recurse. But the following code:

test = array(
    'name' => 'sean',
    'dob' => '12-20',
    'parents' => array(
        'father' => 'tommy',
        'mother' => 'darcy'
    )
);

foreach(range(1, 3) as $depth) {
    echo "-----------------\n depth: $depth\n";
    print_r(json_decode(json_encode($test), true, $depth));
}

Produces this output:

-----------------
 depth: 1
-----------------
 depth: 2
-----------------
 depth: 3
Array
(
    [name] => sean
    [dob] => 12-20
    [parents] => Array
        (
            [father] => tommy
            [mother] => darcy
        )

)

What I would expect is a depth of 1 to show “name” and “dob”, and a depth of 2 to show the parents, also. I don’t get why a depth of 1 or 2 displays nothing at all.

Can anyone explain to me what I’m not understanding?

How to&Answers:

The documentation says why.

NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Answer:

the problem here is that you didn’t understand the depth parameter correctly

the depth of your test array is 3 and so it will not be printed in the first two iterations and a null value is returned

but in the 3rd iteration it gets printed because its depth is equal to the $depth [i.e. 3]

Answer:

In addition to @Explosion Pills answer, you expect json_decode to work as json_encode should.

According to documentation you can now specify your own limit, to encode arrays/objects. Which simply means that it will skip going deeper than specified level.

For json_decode it’s different – it always try to parse whole JSON string, because it simply can’t stop, and skip deeper parts without parsing the whole string. This is why depth limit causes the function to return NULL in this cases.

json_encode can stop and skip deeper parts, as the data structure is already defined in the memory.

Notice that $depth for json_encode was added for PHP version 5.5.0 (json_decode has it since 5.3.0). Check changelog here.