PHP : json_decode depth errors

In this tutorial learn how to search error while json_encode() using depth errors. While,converting json_decode finding depth errors from json, let's go with 

Example index.php 



<?php

$json = json_encode(
    array(
        1 => array(
            'User' => array(
                '1',
                'Jason'
            ),
            'Address' => array(
                'New Yourk',
                'USA'
            )
        ),
        
        2 => array(
            'User' => array(
                '2',
                'Jack'
            ),
            'Address' => array(
                'London',
                'UK'
            )
        )
    )
);

// Define the errors.
$constants = get_defined_constants(true);
$json_errors = array();
foreach ($constants["json"] as $name => $value) {
    if (!strncmp($name, "JSON_ERROR_", 11)) {
        $json_errors[$value] = $name;
    }
}

// Show the errors for different depths.
foreach (range(4, 3, -1) as $depth) {
    var_dump(json_decode($json, true, $depth));
    echo 'Last error: ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
}


The above example will output:


array(2) {
  [1]=>
  array(2) {
    ["User"]=>
    array(2) {
      [0]=>
      string(1) "1"
      [1]=>
      string(5) "Jason"
    }
    ["Address"]=>
    array(2) {
      [0]=>
      string(9) "New Yourk"
      [1]=>
      string(3) "USA"
    }
  }
  [2]=>
  array(2) {
    ["User"]=>
    array(2) {
      [0]=>
      string(1) "2"
      [1]=>
      string(4) "Jack"
    }
    ["Address"]=>
    array(2) {
      [0]=>
      string(6) "London"
      [1]=>
      string(2) "UK"
    }
  }
}
Last error: JSON_ERROR_NONE

NULL
Last error: JSON_ERROR_DEPTH

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...