The json_decode Function

The json_decode function converts a string in JSON format into PHP variables. The first parameter of the function accepts a JSON string, the second - a conversion flag (optional), and the third - the recursion depth (optional). By default, the function returns associative arrays.

Syntax

phpjson_decode(string, [assoc = false], [depth = 512], [flags = 0]);

Example

Convert a simple JSON string to a PHP object:

php<?php
  $json = '{"a":1,"b":2,"c":3}';
  $res = json_decode($json);
  print_r($res);
?>

Code execution result:

phpstdClass Object
(
  [a] => 1
  [b] => 2
  [c] => 3
)

Example

Convert a JSON string to an associative array:

php<?php
  $json = '{"a":1,"b":2,"c":3}';
  $res = json_decode($json, true);
  print_r($res);
?>

Code execution result:

php[
  'a' => 1,
  'b' => 2,
  'c' => 3,
]

Example

Handling invalid JSON:

php<?php
  $json = '{"a":1,"b":2,"c":3';
  $res = json_decode($json);
  var_dump($res);
?>

Code execution result:

phpNULL

See Also

  • the json_encode function,
    which converts PHP data to JSON
  • the serialize function,
    which converts PHP data to a string