How do I decode JSON in PHP?

To decode a JSON file or string in PHP, you can use the json_decode(string, assoc, depth, options) function. The first parameter specifies the string to be decoded. The second parameter is optional and specifies whether the returned object should be converted to an associative array. By default, the json_decode() function recursively decodes JSON with a depth of 512. You can set a different recursion depth in the third parameter. If the JSON cannot be decoded or the nesting depth of the data is greater than the recursion limit, the decode function returns NULL. In this PHP decode JSON example, we use the json_decode() function to convert a JSON string into a PHP variable using default values. Click Execute to run the PHP JSON Decode Example online and see the result.
How do I decode JSON in PHP? Execute
<?php
$json = '{"Leo":25,"Alice":37,"Tim":43}';

print_r (json_decode($json));
?>
Updated: Viewed: 895 times

What is JSON?

JSON (JavaScript Object Notation) is a standard text-based data interchange format that is based on the JavaScript object syntax. JSON is widely used for data exchange between applications written in many programming languages, including JavaScript, PHP, Java, C++, C#, Go, Python, and many more.

PHP JSON Decode Function

In PHP, the json_decode() function is used to decode a JSON string into a PHP object. The result object can be any PHP data type, except for resource pointers such as a database or file descriptor. Following is the syntax of the json_decode() function:

PHP json_decode() Syntax
json_decode(string, assoc, depth, options)

Where:
  • string: specifies the value to be decoded. It only works with UTF-8 encoded strings.
  • assoc (Optional): specifies a boolean value If set to "true", the returned object will be converted to an associative array. If set to "false", it returns an object. The default value is "false".
  • depth (Optional): specifies the recursion depth. The default JSON decoding recursion depth is 512.
  • options (Optional): specifies a bitmask that determines how JSON objects will be converted to PHP objects. The decode function supports the following bitmasks: JSON_BIGINT_AS_STRING, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_OBJECT_AS_ARRAY, JSON_THROW_ON_ERROR. You can learn more about JSON decodeding bitmasks in the PHP documentation.
PHP json_decode() Example
<?php
$json = '{"Leo":25,"Alice":37,"Tim":43}';

print_r (json_decode($json));
?>

#output: stdClass Object
(
    [Leo] => 25
    [Alice] => 37
    [Tim] => 43
)

See also