PHP Function Reference

PHP json_decode() Function



The PHP json_decode() function decodes a JSON encoded string and converts it into a PHP variable.

Syntax

json_decode(json, associative, depth, flags)

Parameters

json Required. Specify the JSON string being decoded. It only works with UTF-8 encoded strings.
associative Optional. If set to true, JSON objects will be returned as associative arrays. If set to false, JSON objects will be returned as objects. When null, JSON objects will be returned as associative arrays or objects depending on whether JSON_OBJECT_AS_ARRAY is set in the flags.
depth Optional. Specify the maximum nesting depth of the structure being decoded. Default is 512.
flags Optional. Specify Bitmask of JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR. The behavior of these constants is described on the JSON constants page.

Return Value

Returns the value encoded in JSON in appropriate PHP type. Values true, false and null are returned as true, false and null respectively. null is returned if the JSON cannot be decoded or if the encoded data is deeper than the nesting limit.

Example: json_decode() example

The example below shows the usage of json_decode() function.

<?php
//declaring a JSON string
$jsonObj = '{"a":10,"b":20,"c":30}';

//using json_decode() function to 
//decode the JSON string
var_dump(json_decode($jsonObj));
echo "\n";
var_dump(json_decode($jsonObj, true));
?>

The output of the above code will be:

object(stdClass)#1 (3) {
  ["a"]=>
  int(10)
  ["b"]=>
  int(20)
  ["c"]=>
  int(30)
}

array(3) {
  ["a"]=>
  int(10)
  ["b"]=>
  int(20)
  ["c"]=>
  int(30)
}

Example: accessing object properties

The example below shows how to access properties from the PHP object.

<?php
//declaring a JSON string
$jsonObj = '{"a":10,"b":20,"c":30}';

//using json_decode() function to 
//decode the JSON string
$obj = json_decode($jsonObj);

echo $obj->a;
echo "\n";
echo $obj->b;
echo "\n";
echo $obj->c;
?>

The output of the above code will be:

10
20
30

Example: accessing values from associative array

The example below shows how to access values from the PHP associative array.

<?php
//declaring a JSON string
$jsonObj = '{"a":10,"b":20,"c":30}';

//using json_decode() function to 
//decode the JSON string
$arr = json_decode($jsonObj, true);

echo $arr['a'];
echo "\n";
echo $arr['b'];
echo "\n";
echo $arr['c'];
?>

The output of the above code will be:

10
20
30

❮ PHP JSON Reference