Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of using depth in JSON encode?

Tags:

json

php

I have this example code:

$array = array(

    'GiamPy' => array(
            'Age' => '18',      
            'Password' => array(
                    'password' => '1234',
                    'salt' => 'abcd',
                    'hash' => 'whirlpool'
            ),  
        'Something' => 'Else'
    )

);

echo json_encode($array, JSON_PRETTY_PRINT);

I have seen in the PHP documentation that, since PHP 5.5.0 (thus recently), json_encode allows a new parameter which is the depth.

  1. What is its purpose?
  2. Why would I ever need it?
  3. Why has it been added in PHP 5.5.0?
like image 356
GiamPy Avatar asked Jan 05 '14 19:01

GiamPy


People also ask

What is the use of JSON encode?

The json_encode() function is used to encode a value to JSON format.

What is JSON decode and encode?

JsonEncoder and JsonDecoder​A decoder is a function that takes a CharSequence and returns a Right with the decoded value or a Left with an error message. An encoder is a function that takes a value of type A and returns a CharSequence that represents the encoded value (JSON string).

What is JSON encoded string?

The method JSON. stringify(student) takes the object and converts it into a string. The resulting json string is called a JSON-encoded or serialized or stringified or marshalled object.

How can access JSON encode data in PHP?

To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.


1 Answers

The option limits the depth that will be processed (d'uh). The depth of an array is measured by how deep it is nested. This is an array of depth 1:

array(
    'foo',
    'bar',
    'baz'
)

This is an array of depth 2:

array(
    array(
        'foo'
    ),
    array(
        'bar'
    ),
    array(
        'baz'
    )
)

// ------ depth ------>

If the input surpasses the maximum depth (by default 512), json_encode will simply return false.

Why you may use this is debatable, you may want to protect yourself from inadvertent infinite recursion or too much resource use. An array which is deeper than 512 levels probably has infinitely recursive references and cannot be serialised. But if you are sure your array is not infinitely recursive yet is deeper than 512, you may want to increase this limit explicitly. You may also want to lower the limit as a simple error catcher; say you expect the result to have a maximum depth but your input data may be somewhat unpredictable.

like image 175
deceze Avatar answered Oct 01 '22 23:10

deceze