Parameters

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.

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_UNESCAPED_UNICODE. The behaviour of these
constants is described on
the JSON constants page.

Notes

In the event of a failure to encode, json_last_error()
can be used to determine the exact nature of the error.

Note:

When encoding an array, if the keys are not a continuous numeric
sequence starting from 0, all keys are encoded as strings, and
specified explicitly for each key-value pair.

Note:

Like the reference JSON encoder, json_encode() will
generate JSON that is a simple value (that is, neither an object nor an
array) if given a string, integer,
float or boolean as an input
value. While most decoders will accept these values
as valid JSON, some may not, as the specification is ambiguous on this
point.

To summarise, always test that your JSON decoder can handle the output you
generate from json_encode().

I came across the "bug" where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.

You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA.

PHP 5.5 has it right of course (if encoding fails, return false) but its likely to introduce errors when updating to 5.5 because previously you could get the rest of the JSON even when one string was not in UTF8 (if this string wasn't used, you'd never notify it's nulled)

Note that if you try to encode an array containing non-utf values, you'll get null values in the resulting JSON string. You can batch-encode all the elements of an array with the array_map function:<?php$encodedArray = array_map(utf8_encode, $rawArray);?>

A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.

For users of php 5.1.6 or lower, a native json_encode function. This version handles objects, and makes proper distinction between [lists] and {associative arrays}, mixed arrays work as well. It can handle newlines and quotes in both keys and data.

This function will convert non-ascii symbols to "\uXXXX" format as does json_encode.

Besides that, it outputs exactly the same string as json_encode. Including UTF-8 encoded 2-, 3- and 4-byte characters. It is a bit faster than PEAR/JSON::encode, but still slow compared to php 5.3's json_encode. It encodes any variable type exactly as the original.

[EDIT BY danbrown AT php DOT net: Contains a bugfix by the original poster on 08-DEC-2010 with the following message: "I discovered a rather bad bug in my __json_encode function below. On versions prior to php 5.2.5, all 'f' characters are escaped to '\f'. This is because addcslashes in php < 5.2 doesn't understand \f as 'formfeed'."]

If you are planning on using this function to serve a json file, it's important to note that the json generated by this function is not ready to be consumed by javascript until you wrap it in parens and add ";" to the end.

It took me a while to figure this out so I thought I'd save others the aggravation.

$file='rss.xml';$arr = simplexml_load_file($file);//this creates an object from the xml file$json= '('.json_encode($arr).');'; //must wrap in parens and end with semicolonprint_r($_GET['callback'].$json); //callback is prepended for json-p?>

For anyone who has run into the problem of private properties not being added, you can simply implement the IteratorAggregate interface with the getIterator() method. Add the properties you want to be included in the output into an array in the getIterator() method and return it.

For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn't want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.

Note that, because javascript converts JSON data into either nested named objects OR vector arrays, it's quite difficult to represent mixed PHP arrays (arrays with both numerical and associative indexes) well in JSON. This function does something funky if you pass it a mixed array -- see the comments for details.

I don't make a claim that this function is by any means complete (for example, it doesn't handle objects) so if you have any improvements, go for it.

<?php

/**
* Converts an associative array of arbitrary depth and dimension into JSON representation.
*
* NOTE: If you pass in a mixed associative and vector array, it will prefix each numerical
* key with "key_". For example array("foo", "bar" => "baz") will be translated into
* {"key_0": "foo", "bar": "baz"} but array("foo", "bar") would be translated into [ "foo", "bar" ].
*
* @param $array The array to convert.
* @return mixed The resulting JSON string, or false if the argument was not an array.
* @author Andy Rusterholz
*/
function array_to_json( $array ){

If, for some reason you need to force a single object to be an array, you can use array_values() -- this can be necessary if you have an array with only one entry, as json_encode will assign it as an object otherwise :

In my application, I had objects that modeled database rows with a few one to many relationships, so one object may have an array of other objects.

I wanted to make the object properties private and use getters and setters, but I needed them to be serializable to json without losing the private variables. (I wanted to promote good coding practices but I needed the properties on the client side.) Because of this, I needed to encode not only the normal private properties but also properties that were arrays of other model objects. I looked for awhile with no luck, so I coded my own:

You can place these methods in each of your classes, or put them in a base class, as I've done. (But note that for this to work, the children classes must declare their properties as protected so the parent class has access)

[NOTE BY danbrown AT php DOT net: Includes a bugfix by (robbiz233 AT hotmail DOT com) on 18-SEP-2010, to replace:
$newArray[$key] = utf8json($inArray);
with:
$newArray[$key] = utf8json($val);"
in the given function.]

It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:

We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.

This can lead to problems within javascript functions expecting the values to be numeric.

This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.

The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.

If you're wondering whether a JSON string can be an analog of an XML document, the answer is probably "nope." XML supports attributes, but JSON does not. A JSON string generated by json_encode(), when called on a SimpleXML object, will not have the attributes and no error or exception will issue - the original data will simply be lost. To see this in action:<?php error_reporting(E_ALL);echo '<pre>';

json_encode "only works with UTF-8 encoded data." so if there is any chance that users influence the variable you're about to encode to json, you should first recursively encode to UTF-8.

There are several comments doing that, but some only traverse the input array 1 level deep. Others write full fledged recursive functions themselves. Whereas as of PHP5 you could also utilize array_walk_recursive

The JSON_NUMERIC_CHECK flag introduced in 5.3.0 comes in very handy when handling numbers encapsulated in a string (database results and post requests are always encoded as string types, for example). Sending over variables from a database result directly (as string) would cause the json_encode() function to quote them, which in turn would make the Javascript store them as strings. As Javascript isn't loosely typed, some libraries could break on this, when attempting to use one of those variables as row id in a data store for instance. Using the aforementioned flag can prevent this from happening.

According to the JSON spec, only objects and arrays can be represented; the JSON_FORCE_OBJECT flag available since PHP 5.3 does not change this behaviour. If you're using this to produce JSON that will be exchanged with other systems, adjust your output accordingly.

<?php$json = preg_replace('/^([^[{].*)$/', '[$1]', $json);?>

The json_decode function accepts these JSON fragments without complaint.

json_encode also won't handle objects that do not directly expose their internals but through the Iterator interface. These two function will take care of that:

<?php

/** * Convert an object into an associative array * * This function converts an object into an associative array by iterating * over its public properties. Because this function uses the foreach * construct, Iterators are respected. It also works on arrays of objects. * * @return array */function object_to_array($var) {$result = array();$references = array();

Obviously, this function has trouble encoding arrays with empty string keys (''). I have just noticed that (because I was using a function in PHP under PHP4). When I switched to PHP5's json_encode, I noticed that browsers could not correctly parse the encoded data. More investigation maybe needed for a bug report, but this quick note may save somebody several hours.

Also, it manifests on Linux in 5.2.1 (tested on two boxes), on my XP with PHP5.2.3 json_encode() works just great! However, both 5.2.1 and 5.2.3 phpinfo()s show that the json version is 1.2.1 so might be Linux issue

You need to replace the nul character manually as addcslashes() won't do it right way. But BEWARE, this is only solution for common strings, other "unusual wild characters" like ESC, \b, \a etc. are not handled.

I had trouble putting the results of mysql_fetch_assoc() through json_encode: numbers being returned from the query were being quoted in the JSON output (i.e., they were being treated as strings). In order to fix this, it is necessary to explicitly cast each element of the array before json_encode() is called.

The following code uses metadata from a MySQL query result to do this casting.

Another way for pre-5.2.0 PHP users is using rawurlencode() in PHP to encode a string and decodeURIComponent() in javascript to decode it. I have written following class to handle PHP arrays and convert them to javascript format. It uses object notation for associative arrays and arrays for the other. Nesting is supported. True, false, integers, floats and null values are presented in respective javascript syntax.

Use: convert an array in PHP using this class, load it into the browser using ajax and then decode the strings in the resulting object using javascript function decodeData (below).

All of the example results have passed json validator so it shoud be allright. Feel free to use this.

There is a gotcha that keeps getting me with JSON_NUMERIC_CHECK. At first it seems like the greatest thing in the world if you are encoding data pulled from a db because it turns numeric strings into seemingly appropriate ints or floats. Use with caution. I've been surprised a number of times by "numbers" that really are strings ie really precise lat/long coords. json_encode with the JSON_NUMERIC_CHECK will encode these as floats but the precision of the data is so large that php actually rounds the number off. In this case I had to rework my code so that it didn't use JSON_NUMERIC_CHECK and I manually cast fields as ints or floats as appropriate and skipped my lat/long fields so that they stayed numeric strings.

Calling something like $t = json_encode($this->getIterator()); will give you almost what you want:<?php {"kitID":"Kit_Essentials-Books.txt","kitName":"Essential Books","productArray":{"0470043601":{"Category":"Food","ASIN":"0470043601"} } } ?>

Notice that the productArray is converted to an object ignoring the cast I put in front, which is not what I wanted. I haven't figured out how to make sure that encodes as an array.

Regardless, bringing that JSON back into an object using json_decode() will give you just a std object, and the only way I've found to get it into the proper object type is to use a constructor that instantiates the object the way it's supposed to be (see __construct($var) above). Like this:<?php

> Note:> PHP implements a superset of JSON - it will also encode and> decode scalar types and NULL. The JSON standard only supports> these values when they are nested inside an array or an object.

This is patently false. Nowhere in the standard does it say that only objects or arrays may be represented. The standard lays out what a value consists of and any value type is legal. Interpreters on other platforms which don't allow scalar types are incorrectly (and probably terribly) coded.

When Using Libraries such as Prototype you may find that once in a while when you return what you believe to be a empty array it will have a different behavior (vis a vis enumerables) than when you give it an associative array. To "fix" this, on your JS you may want to look for extended object properties to verify if it is an empty array or an ocject.

Note that json_encode always escapes a solidus (forward slash, %x2F).This may be a problem if you are encoding a URL.It's been recognised and fixed in September 2010:http://bugs.php.net/bug.php?id=49366But escaping will still be the default behaviour.A crude repair can be done withstr_replace('\\/', '/', $jsonEncoded)

You may run into trouble when you need to call functions. In my case I had to fire a function based on a button pressed in the flexigrid javascript component.

My solution in the project was:

<?php

$jsonify = array('onpress'=>'functionName');

// The part between braces in the regex is somewhat rough
// but it will do the job. Afterall, you don't want this to be
// used by a visitor :)
$regex = '/"onpress":"([\w\-\.]+)"/i';
$replace = '"onpress":$1';
$jsonified = preg_replace($regex, $replace, json_encode($jsonify));

?>

But you can extend this for your own needs. By altering the regex and replace vars: