- string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
- mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
|value||The value being encoded. Can be any type except a resource. All string data must be UTF-8 encoded.|
|options||Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT, JSON_PRESERVE_ZERO_FRACTION, JSON_UNESCAPED_UNICODE, JSON_PARTIAL_OUTPUT_ON_ERROR. The behaviour of these constants is described on the JSON constants page.|
|depth||Set the maximum depth. Must be greater than zero.|
|json||The json string being decoded. This function only works with UTF-8 encoded strings.|
|assoc||Should function return associative array instead of objects.|
|options||Bitmask of JSON decode options. Currently only JSON_BIGINT_AS_STRING is supported (default is to cast large integers as floats)|
- json_decode handling of invalid JSON is very flaky, and it is very hard to reliably determine if the decoding succeeded, json_decode returns null for invalid input, even though null is also a perfectly valid object for JSON to decode to. To prevent such problems you should always call json_last_error every time you use it.
Debugging JSON errors
json_decode fails to parse the string provided, it will return
false. PHP itself will not raise any errors or warnings when this happens, the onus is on the user to use the json_last_error() and json_last_error_msg() functions to check if an error occurred and act accordingly in your application (debug it, show an error message, etc.).
The following example shows a common error when working with JSON, a failure to decode/encode a JSON string (due to the passing of a bad UTF-8 encoded string, for example).
json_last_error_msg() returns a human readable message of the last error that occurred when trying to encode/decode a string.
- This function will always return a string, even if no error occurred.
The default non-error string is
- It will return
falseif some other (unknown) error occurred
- Careful when using this in loops, as json_last_error_msg will be overridden on each iteration.
You should only use this function to get the message for display, not to test against in control statements.
This function doesn't exist before PHP 5.5. Here is a polyfill implementation:
json_last_error() returns an integer mapped to one of the pre-defined constants provided by PHP.
|No error has occurred|
|The maximum stack depth has been exceeded|
|Invalid or malformed JSON|
|Control character error, possibly incorrectly encoded|
|Syntax error (since PHP 5.3.3)|
|Malformed UTF-8 characters, possibly incorrectly encoded (since PHP 5.5.0)|
|One or more recursive references in the value to be encoded|
|One or more NAN or INF values in the value to be encoded|
|A value of a type that cannot be encoded was given|
Decoding a JSON string
json_decode() function takes a JSON-encoded string as its first parameter and parses it into a PHP variable.
json_decode() will return an object of \stdClass if the top level item in the JSON object is a dictionary or an indexed array if the JSON object is an array. It will also return scalar values or
NULL for certain scalar values, such as simple strings,
"null". It also returns
NULL on any error.
var_dump() to view the types and values of each property on the object we decoded above.
Output (note the variable types):
Note: The variable types in JSON were converted to their PHP equivalent.
Output (note the array associative structure):
The second parameter (
$assoc) has no effect if the variable to be returned is not an object.
Note: If you use the
$assoc parameter, you will lose the distinction between an empty array and an empty object. This means that running
json_encode() on your decoded output again, will result in a different JSON structure.
If the JSON string has a "depth" more than 512 elements (20 elements in versions older than 5.2.3, or 128 in version 5.2.3) in recursion, the function
NULL. In versions 5.3 or later, this limit can be controlled using the third parameter (
$depth), as discussed below.
According to the manual:
PHP implements a superset of JSON as specified in the original » RFC 4627 - it will also encode and decode scalar types and NULL. RFC 4627 only supports these values when they are nested inside an array or an object. Although this superset is consistent with the expanded definition of "JSON text" in the newer » RFC 7159 (which aims to supersede RFC 4627) and » ECMA-404, this may cause interoperability issues with older JSON parsers that adhere strictly to RFC 4627 when encoding a single scalar value.
This means, that, for example, a simple string will be considered to be a valid JSON object in PHP:
But simple strings, not in an array or object, are not part of the RFC 4627 standard. As a result, such online checkers as JSLint, JSON Formatter & Validator (in RFC 4627 mode) will give you an error.
There is a third
$depth parameter for the depth of recursion (the default value is
512), which means the amount of nested objects inside the original object to be decoded.
There is a fourth
$options parameter. It currently accepts only one value,
JSON_BIGINT_AS_STRING. The default behavior (which leaves off this option) is to cast large integers to floats instead of strings.
Invalid non-lowercased variants of the true, false and null literals are no longer accepted as valid input.
So this example:
Before PHP 5.6:
Similar behavior occurs for
json_decode() will return
NULL if the string cannot be converted.
It is not safe to rely only on the return value being
NULL to detect errors. For example, if the JSON string contains nothing but
json_decode() will return
null, even though no error occurred.
Encoding a JSON string
json_encode function will convert a PHP array (or, since PHP 5.4, an object which implements the
JsonSerializable interface) to a JSON-encoded string. It returns a JSON-encoded string on success or FALSE on failure.
During encoding, the PHP data types string, integer, and boolean are converted to their JSON equivalent. Associative arrays are encoded as JSON objects, and – when called with default arguments – indexed arrays are encoded as JSON arrays. (Unless the array keys are not a continuous numeric sequence starting from 0, in which case the array will be encoded as a JSON object.)
Since PHP 5.3, the second argument to
json_encode is a bitmask which can be one or more of the following.
As with any bitmask, they can be combined with the binary OR operator
Forces the creation of an object instead of an array
Ensures the following conversions during encoding:
Ensures numeric strings are converted to integers.
Allows encoding to continue if some unencodable values are encountered.
Ensures that floats are always encoded as floats.
When used with
JSON_UNESCAPED_UNICODE was changed in version 7.1.
Header json and the returned response
By adding a header with content type as JSON:
The header is there so your app can detect what data was returned and how it should handle it.
Note that : the content header is just information about type of returned data.
If you are using UTF-8, you can use :
Example jQuery :
Using JsonSerializable in an Object
When you build REST API's, you may need to reduce the information of an object to be passed to the client application. For this purpose, this example illustrates how to use the
In this example, the class
User actually extends a DB model object of a hypotetical ORM.
JsonSerializable implementation to the class, by providing the
Now in your application controller or script, when passing the object User to
json_encode() you will get the return json encoded array of the
jsonSerialize() method instead of the entire object.
properties values example.
This will both reduce the amount of data returned from a RESTful endpoint, and allow to exclude object properties from a json representation.
Using Private and Protected Properties with
To avoid using JsonSerializable, it is also possible to use private or protected properties to hide class information from
json_encode() output. The Class then does not need to implement \JsonSerializable.
The json_encode() function will only encode public properties of a class into JSON.