Documentation on json_encode

json_encode = Returns the JSON representation of a value

Returns a string containing the JSON representation of value.

value The value being encoded. Can be any type except a resource. All string data must be UTF-8 encoded. Note: 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_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.

Usage, params, and more on json_encode

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

value The value being encoded. Can be any type except a resource. All string data must be UTF-8 encoded. Note: 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_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.

Returns a JSON encoded string on success or FALSE on failure.

Notes and warnings on json_encode

Basic example of how to use: json_encode

Example #1 A json_encode() example

<?php
$arr 
= array('a' => 1'b' => 2'c' => 3'd' => 4'e' => 5);

echo 
json_encode($arr);
?>

The above example will output:

 {"a":1,"b":2,"c":3,"d":4,"e":5} 

Example #2 A json_encode() example showing some options in use

<?php
$a 
= array('<foo>',"'bar'",'"baz"','&blong&'"\xc3\xa9");

echo 
"Normal: ",  json_encode($a), "\n";
echo 
"Tags: ",    json_encode($aJSON_HEX_TAG), "\n";
echo 
"Apos: ",    json_encode($aJSON_HEX_APOS), "\n";
echo 
"Quot: ",    json_encode($aJSON_HEX_QUOT), "\n";
echo 
"Amp: ",     json_encode($aJSON_HEX_AMP), "\n";
echo 
"Unicode: "json_encode($aJSON_UNESCAPED_UNICODE), "\n";
echo 
"All: ",     json_encode($aJSON_HEX_TAG JSON_HEX_APOS JSON_HEX_QUOT JSON_HEX_AMP JSON_UNESCAPED_UNICODE), "\n\n";

$b = array();

echo 
"Empty array output as array: "json_encode($b), "\n";
echo 
"Empty array output as object: "json_encode($bJSON_FORCE_OBJECT), "\n\n";

$c = array(array(1,2,3));

echo 
"Non-associative array output as array: "json_encode($c), "\n";
echo 
"Non-associative array output as object: "json_encode($cJSON_FORCE_OBJECT), "\n\n";

$d = array('foo' => 'bar''baz' => 'long');

echo 
"Associative array always output as object: "json_encode($d), "\n";
echo 
"Associative array always output as object: "json_encode($dJSON_FORCE_OBJECT), "\n\n";
?>

The above example will output:

 Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"] Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"] Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"] Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"] Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"] Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"] All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"] Empty array output as array: [] Empty array output as object: {} Non-associative array output as array: [[1,2,3]] Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}} Associative array always output as object: {"foo":"bar","baz":"long"} Associative array always output as object: {"foo":"bar","baz":"long"} 

Example #3 JSON_NUMERIC_CHECK option example

<?php
echo "Strings representing numbers automatically turned into numbers".PHP_EOL;
$numbers = array('+123123''-123123''1.2e3''0.00001');
var_dump(
 
$numbers,
 
json_encode($numbersJSON_NUMERIC_CHECK)
);
echo 
"Strings containing improperly formatted numbers".PHP_EOL;
$strings = array('+a33123456789''a123');
var_dump(
 
$strings,
 
json_encode($stringsJSON_NUMERIC_CHECK)
);
?>

The above example will output something similar to:

 Strings representing numbers automatically turned into numbers array(4) { [0]=> string(7) "+123123" [1]=> string(7) "-123123" [2]=> string(5) "1.2e3" [3]=> string(7) "0.00001" } string(28) "[123123,-123123,1200,1.0e-5]" Strings containing improperly formatted numbers array(2) { [0]=> string(13) "+a33123456789" [1]=> string(4) "a123" } string(24) "["+a33123456789","a123"]" 

Example #4 Sequential versus non-sequential array example

<?php
echo "Sequential array".PHP_EOL;
$sequential = array("foo""bar""baz""blong");
var_dump(
 
$sequential,
 
json_encode($sequential)
);

echo 
PHP_EOL."Non-sequential array".PHP_EOL;
$nonsequential = array(1=>"foo"2=>"bar"3=>"baz"4=>"blong");
var_dump(
 
$nonsequential,
 
json_encode($nonsequential)
);

echo 
PHP_EOL."Sequential array with one key unset".PHP_EOL;
unset(
$sequential[1]);
var_dump(
 
$sequential,
 
json_encode($sequential)
);
?>

The above example will output:

 Sequential array array(4) { [0]=> string(3) "foo" [1]=> string(3) "bar" [2]=> string(3) "baz" [3]=> string(5) "blong" } string(27) "["foo","bar","baz","blong"]" Non-sequential array array(4) { [1]=> string(3) "foo" [2]=> string(3) "bar" [3]=> string(3) "baz" [4]=> string(5) "blong" } string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}" Sequential array with one key unset array(3) { [0]=> string(3) "foo" [2]=> string(3) "baz" [3]=> string(5) "blong" } string(33) "{"0":"foo","2":"baz","3":"blong"}" 

Example #5 JSON_PRESERVE_ZERO_FRACTION option example

<?php
var_dump
(json_encode(12.0JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
?>

The above example will output:

 string(4) "12.0" string(2) "12" 

Other code examples of json_encode being used

Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?

Just watch this usecase:

<?php
// International phone number
json_encode(array('phone_number' => '+33123456789'), JSON_NUMERIC_CHECK);
?>

And then you get this JSON:

{"phone_number":33123456789}

Maybe it makes sense for PHP (as is_numeric('+33123456789') returns true), but really, casting it as an int?!

So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!

This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed under GNU/AGPLv3 or GPLv3 like you prefer):

<?php

function json_readable_encode($in, $indent = 0, $from_array = false)
{
   
$_myself = __FUNCTION__;
   
$_escape = function ($str)
    {
        return
preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

   
$out = '';

    foreach (
$in as $key=>$value)
    {
       
$out .= str_repeat("\t", $indent + 1);
       
$out .= "\"".$_escape((string)$key)."\": ";

        if (
is_object($value) || is_array($value))
        {
           
$out .= "\n";
           
$out .= $_myself($value, $indent + 1);
        }
        elseif (
is_bool($value))
        {
           
$out .= $value ? 'true' : 'false';
        }
        elseif (
is_null($value))
        {
           
$out .= 'null';
        }
        elseif (
is_string($value))
        {
           
$out .= "\"" . $_escape($value) ."\"";
        }
        else
        {
           
$out .= $value;
        }

       
$out .= ",\n";
    }

    if (!empty(
$out))
    {
       
$out = substr($out, 0, -2);
    }

   
$out = str_repeat("\t", $indent) . "{\n" . $out;
   
$out .= "\n" . str_repeat("\t", $indent) . "}";

    return
$out;
}

?>

Because json_encode() only deals with utf8, it is often necessary to convert all the string values inside an array to utf8. I've created these two functions:   

<?php
function utf8_encode_all($dat) // -- It returns $dat encoded to UTF8
{
  if (
is_string($dat)) return utf8_encode($dat);
  if (!
is_array($dat)) return $dat;
 
$ret = array();
  foreach(
$dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
  return
$ret;
}
/* ....... */

function utf8_decode_all($dat) // -- It returns $dat decoded from UTF8
{
  if (
is_string($dat)) return utf8_decode($dat);
  if (!
is_array($dat)) return $dat;
 
$ret = array();
  foreach(
$dat as $i=>$d) $ret[$i] = utf8_decode_all($d);
  return
$ret;
}
/* ....... */
?>

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.

e.g.:

<?php
$myarray
= Array('isa', 'dalawa', 'tatlo');
var_dump($myarray);
/* output
array(3) {
  [0]=>
  string(3) "isa"
  [1]=>
  string(6) "dalawa"
  [2]=>
  string(5) "tatlo"
}
*/
?>

As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array.

<?php
$myarray
= Array('isa', 'dalawa', 'tatlo');

unset(
$myarray[1]);
var_dump($myarray);
/* output
array(2) {
  [0]=>
  string(3) "isa"
  [2]=>
  string(5) "tatlo"
}
*/
?>

Unsetting an element will also remove the keys. json_encode() will now assume that this is an object, and will encode it as such.

SOLUTION: Use array_values() to re-index the array.

Hey everyone,

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)

<?php
abstract class Model {
  
   public function
toArray() {
        return
$this->processArray(get_object_vars($this));
    }
   
    private function
processArray($array) {
        foreach(
$array as $key => $value) {
            if (
is_object($value)) {
               
$array[$key] = $value->toArray();
            }
            if (
is_array($value)) {
               
$array[$key] = $this->processArray($value);
            }
        }
       
// If the property isn't an object or array, leave it untouched
       
return $array;
    }
   
    public function
__toString() {
        return
json_encode($this->toArray());
    }
  
}
?>

Externally, you can just call

<?php
   
echo $theObject;
   
//or
   
echo json_encode($theObject->toArray());
?>

And you'll get the json for that object. Hope this helps someone!

For PHP5.3 users who want to emulate JSON_UNESCAPED_UNICODE, there is simple way to do it:
<?php
function my_json_encode($arr)
{
       
//convmap since 0x80 char codes so it takes all multibyte codes (above ASCII 127). So such characters are being "hidden" from normal json_encoding
       
array_walk_recursive($arr, function (&$item, $key) { if (is_string($item)) $item = mb_encode_numericentity($item, array (0x80, 0xffff, 0, 0xffff), 'UTF-8'); });
        return
mb_decode_numericentity(json_encode($arr), array (0x80, 0xffff, 0, 0xffff), 'UTF-8');

}
?>

Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.

Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.

In a Latin-1 encoded file, write this:
<?php
$a
= array('é', 1);
var_dump(json_encode($a));
?>

PHP < 5.4:
string(8) "[null,1]"

PHP >= 5.5:
bool(false)

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)

This function has weird behavior regarding error reporting in PHP version 5.4 or lower. This kind of warning is raised only if you configure PHP with "display_errors=Off" (!?): "PHP Warning:  json_encode(): Invalid UTF-8 sequence in argument ..."

You can reproduce this behavior:
<?php
// Warning not displayed, not logged
ini_set('display_errors', '1');
json_encode(urldecode('bad utf string %C4_'));

// Warning not displayed but logged
ini_set('display_errors', '0');
json_encode(urldecode('bad utf string %C4_'));
?>

This is considered feature - not-a-bug - by PHP devs:
https://bugs.php.net/bug.php?id=52397
https://bugs.php.net/bug.php?id=63004

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.

Relative speeds:
PHP json_encode: 1x
__json_encode: 31x
PEAR/JSON: 46x

NOTE: I assume the input will be valid UTF-8. I don't know what happens if your data contains illegal Unicode sequences. I tried to make the code fast and compact.

<?php
function __json_encode( $data ) {           
    if(
is_array($data) || is_object($data) ) {
       
$islist = is_array($data) && ( empty($data) || array_keys($data) === range(0,count($data)-1) );
       
        if(
$islist ) {
           
$json = '[' . implode(',', array_map('__json_encode', $data) ) . ']';
        } else {
           
$items = Array();
            foreach(
$data as $key => $value ) {
               
$items[] = __json_encode("$key") . ':' . __json_encode($value);
            }
           
$json = '{' . implode(',', $items) . '}';
        }
    } elseif(
is_string($data) ) {
       
# Escape non-printable or Non-ASCII characters.
        # I also put the \\ character first, as suggested in comments on the 'addclashes' page.
       
$string = '"' . addcslashes($data, "\\\"\n\r\t/" . chr(8) . chr(12)) . '"';
       
$json    = '';
       
$len    = strlen($string);
       
# Convert UTF-8 to Hexadecimal Codepoints.
       
for( $i = 0; $i < $len; $i++ ) {
           
           
$char = $string[$i];
           
$c1 = ord($char);
           
           
# Single byte;
           
if( $c1 <128 ) {
               
$json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1);
                continue;
            }
           
           
# Double byte
           
$c2 = ord($string[++$i]);
            if ( (
$c1 & 32) === 0 ) {
               
$json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128);
                continue;
            }
           
           
# Triple
           
$c3 = ord($string[++$i]);
            if( (
$c1 & 16) === 0 ) {
               
$json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 - 128));
                continue;
            }
               
           
# Quadruple
           
$c4 = ord($string[++$i]);
            if( (
$c1 & 8 ) === 0 ) {
               
$u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1;
           
               
$w1 = (54<<10) + ($u<<6) + (($c2 & 15) << 2) + (($c3>>4) & 3);
               
$w2 = (55<<10) + (($c3 & 15)<<6) + ($c4-128);
               
$json .= sprintf("\\u%04x\\u%04x", $w1, $w2);
            }
        }
    } else {
       
# int, floats, bools, null
       
$json = strtolower(var_export( $data, true ));
    }
    return
$json;
}
?>

[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 need to force an object (ex: empty array) you can also do:

         <?php json_encode( (object)$arr ); ?>

which acts the same as

         <?php json_encode($arr, JSON_FORCE_OBJECT); ?>

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);
?>

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.

<?php
    header
('Content-Type: text/javascript; charset=utf8');
   
header('Access-Control-Allow-Origin: http://www.example.com/');
   
header('Access-Control-Max-Age: 3628800');
   
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
   
   
$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 semicolon
   
print_r($_GET['callback'].$json); //callback is prepended for json-p
?>

<?php

$fp
= fopen('php://stdin', 'r');
$json = @json_encode(array('a' => 'foo', 'b' => $fp));
var_dump($json);

?>

[PHP5.5 or after]
bool(false)

[PHP 5.4 or before]
string(20) "{"a":"foo","b":null}"

This may help others who are seeing null strings returned by json_encode().

This function will encode all array values to utf8 so they are safe for json_encode();

usage:

<?php
json_encode
(utf8json($dataArray));

function
utf8json($inArray) {

    static
$depth = 0;

   
/* our return object */
   
$newArray = array();

   
/* safety recursion limit */
   
$depth ++;
    if(
$depth >= '30') {
        return
false;
    }

   
/* step through inArray */
   
foreach($inArray as $key=>$val) {
        if(
is_array($val)) {
           
/* recurse on array elements */
           
$newArray[$key] = utf8json($val);
        } else {
           
/* encode string values */
           
$newArray[$key] = utf8_encode($val);
        }
    }

   
/* return utf8 encoded array */
   
return $newArray;
}
?>

[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.]

Be careful with floating values in some locales (e.g. russian) with comma (",") as decimal point. Code:

<?php
setlocale
(LC_ALL, 'ru_RU.utf8');

$arr = array('element' => 12.34);
echo
json_encode( $arr );
?>

Output will be:
--------------
{"element":12,34}
--------------

Which is NOT a valid JSON markup. You should convert floating point variable to strings or set locale to something like "LC_NUMERIC, 'en_US.utf8'" before using 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
// Pretend we already have a complex SimpleXML object stored in $xml
$json = json_encode(new SimpleXMLElement($xml->asXML(), LIBXML_NOCDATA));
?>

As json_encode() is recursive, you can use it to serialize whole structure of objects.

<?php
class A {
    public
$a = 1;
    public
$b = 2;
    public
$collection = array();

    function 
__construct(){
        for (
$i=3; $i-->0;){
           
array_push($this->collection, new B);
        }
    }
}

class
B {
    public
$a = 1;
    public
$b = 2;
}

echo
json_encode(new A);
?>

Will give:

{
    "a":1,
    "b":2,
    "collection":[{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    },{
        "a":1,
        "b":2
    }]
}

<?php

// alternative json_encode
function _json_encode($val)
{
    if (
is_string($val)) return '"'.addslashes($val).'"';
    if (
is_numeric($val)) return $val;
    if (
$val === null) return 'null';
    if (
$val === true) return 'true';
    if (
$val === false) return 'false';

   
$assoc = false;
   
$i = 0;
    foreach (
$val as $k=>$v){
        if (
$k !== $i++){
           
$assoc = true;
            break;
        }
    }
   
$res = array();
    foreach (
$val as $k=>$v){
       
$v = _json_encode($v);
        if (
$assoc){
           
$k = '"'.addslashes($k).'"';
           
$v = $k.':'.$v;
        }
       
$res[] = $v;
    }
   
$res = implode(',', $res);
    return (
$assoc)? '{'.$res.'}' : '['.$res.']';
}

?>

Example:
Array
(
    [0] => 7
    [1] => false
    [2] => Array
        (
            ['a'] => Array
                (
                    [0] => 1
                    [1] => 2
                    [3] => Array
                        (
                            [1] => true
                            [2] => 6
                            [0] => 4
                        )
                    [4] => Array
                        (
                            [0] => 'b'
                            [1] => null
                        )
                )
        )
)
Result: [7,false,{"a":{"0":1,"1":2,"3":{"1":true,"2":6,"0":4},"4":["b",null]}}]

This function is more accurate and faster than, for example, that one:
http://www.php.net/manual/ru/function.json-encode.php#89908
(RU: эта функция работает более точно и быстрее, чем указанная выше).

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( !
is_array( $array ) ){
        return
false;
    }

   
$associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
    if(
$associative ){

       
$construct = array();
        foreach(
$array as $key => $value ){

           
// We first copy each key/value pair into a staging array,
            // formatting each key and value properly as we go.

            // Format the key:
           
if( is_numeric($key) ){
               
$key = "key_$key";
            }
           
$key = '"'.addslashes($key).'"';

           
// Format the value:
           
if( is_array( $value )){
               
$value = array_to_json( $value );
            } else if( !
is_numeric( $value ) || is_string( $value ) ){
               
$value = '"'.addslashes($value).'"';
            }

           
// Add to staging array:
           
$construct[] = "$key: $value";
        }

       
// Then we collapse the staging array into the JSON form:
       
$result = "{ " . implode( ", ", $construct ) . " }";

    } else {
// If the array is a vector (not associative):

       
$construct = array();
        foreach(
$array as $value ){

           
// Format the value:
           
if( is_array( $value )){
               
$value = array_to_json( $value );
            } else if( !
is_numeric( $value ) || is_string( $value ) ){
               
$value = '"'.addslashes($value).'"';
            }

           
// Add to staging array:
           
$construct[] = $value;
        }

       
// Then we collapse the staging array into the JSON form:
       
$result = "[ " . implode( ", ", $construct ) . " ]";
    }

    return
$result;
}

?>

WARNING! Do not pass associative arrays if the order is important to you. It seems that while FireFox does keep the same order, both Chrome and IE sort it. Here's a little workaround:

<?php
        $arWrapper
= array();       
       
$arWrapper['k'] = array_keys($arChoices);
       
$arWrapper['v'] = array_values($arChoices);
       
$json = json_encode($arWrapper);
?>

Beware of index arrays :

<?php
echo json_encode(array("test","test","test"));
echo
json_encode(array(0=>"test",3=>"test",7=>"test"));
?>

Will give :

["test","test","test"]
{"0":"test","3":"test","7":"test"}

arrays are returned only if you don't define index.

If I want to encode object whith all it's private and protected properties, then I implements that methods in my object:

<?php
public function encodeJSON()
{
    foreach (
$this as $key => $value)
    {
       
$json->$key = $value;
    }
    return
json_encode($json);
}
public function
decodeJSON($json_str)
{
   
$json = json_decode($json_str, 1);
    foreach (
$json as $key => $value)
    {
       
$this->$key = $value;
    }
}
?>

Or you may extend your class from base class, wich is implements that methods.

Found that much more simple than regular expressions with PHP serialized objects...

Note that this function does not always produce legal JSON.

<?php
$json
= json_encode('foo');
var_dump($json);
//string(5) ""foo""

$json = json_encode(23);
var_dump($json);
//string(2) "23"
?>

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.

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>';

// STARTING FROM XML
$xml = <<<EOD
<?xml version="1.0" ?>
<ingredients>
  <ingredient>
     <name>tomatoes</name>
     <quantity type="cup">4</quantity>
  </ingredient>
  <ingredient>
     <name>salt</name>
     <quantity type="tablespoon">2</quantity>
  </ingredient>
</ingredients>
EOD;

// CREATES AN ARRAY OF SimpleXMLElement OBJECTS
$obj = SimpleXML_Load_String($xml);
var_dump($obj);
echo
PHP_EOL;

// SHOW THE ATTRIBUTES HIDDEN IN THE SimpleXMLElement OBJECTS
foreach ($obj as $sub)
{
    echo
PHP_EOL . (string)$sub->quantity . ' ' . (string)$sub->quantity['type'];
}
echo
PHP_EOL;

// USING THE OBJECT, CREATE A JSON STRING
$jso = json_encode($obj);
echo
htmlentities($jso); // 'type' IS LOST
echo PHP_EOL;

Here's a quick function to pretty-print some JSON. Optimizations welcome, as this was a 10-minute dealie without efficiency in mind:

<?php
// Pretty print some JSON
function json_format($json)
{
   
$tab = "  ";
   
$new_json = "";
   
$indent_level = 0;
   
$in_string = false;

   
$json_obj = json_decode($json);

    if(
$json_obj === false)
        return
false;

   
$json = json_encode($json_obj);
   
$len = strlen($json);

    for(
$c = 0; $c < $len; $c++)
    {
       
$char = $json[$c];
        switch(
$char)
        {
            case
'{':
            case
'[':
                if(!
$in_string)
                {
                   
$new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
                   
$indent_level++;
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
'}':
            case
']':
                if(!
$in_string)
                {
                   
$indent_level--;
                   
$new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
',':
                if(!
$in_string)
                {
                   
$new_json .= ",\n" . str_repeat($tab, $indent_level);
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
':':
                if(!
$in_string)
                {
                   
$new_json .= ": ";
                }
                else
                {
                   
$new_json .= $char;
                }
                break;
            case
'"':
                if(
$c > 0 && $json[$c-1] != '\\')
                {
                   
$in_string = !$in_string;
                }
            default:
               
$new_json .= $char;
                break;                   
        }
    }

    return
$new_json;
}
?>

json_encode($binary) problem: it results in an empty string "" without error.

You will see this happening when encoding binary images, for example.

Use utf8_encode first.

<?php

    $data
= 'éáíúűóüöäÍÓ';
   
$json = json_encode( utf8_encode($data) );

   
// [..]

   
$data = utf8_decode( json_decode($json) );

?>

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 :

<?php
$object
[0] = array("foo" => "bar", 12 => true);

$encoded_object = json_encode($object);
?>

output:

{"1": {"foo": "bar", "12": "true"}}

<?php $encoded = json_encode(array_values($object)); ?>

output:

[{"foo": "bar", "12": "true"}]

So i like to use ISO-8859-1 and a lot of åäöÅÄÖ and not that much for UTF-8 but i need some json stuff so this is what I'm trying to use this lite thing i made...

<?php
function my_json_encode($in) {
 
$_escape = function ($str) {
    return
addcslashes($str, "\v\t\n\r\f\"\\/");
  };
 
$out = "";
  if (
is_object($in)) {
   
$class_vars = get_object_vars(($in));
   
$arr = array();
    foreach (
$class_vars as $key => $val) {
     
$arr[$key] = "\"{$_escape($key)}\":\"{$val}\"";
    }
   
$val = implode(',', $arr);
   
$out .= "{{$val}}";
  }elseif (
is_array($in)) {
   
$obj = false;
   
$arr = array();
    foreach(
$in AS $key => $val) {
      if(!
is_numeric($key)) {
       
$obj = true;
      }
     
$arr[$key] = my_json_encode($val);
    }
    if(
$obj) {
      foreach(
$arr AS $key => $val) {
       
$arr[$key] = "\"{$_escape($key)}\":{$val}";
      }
     
$val = implode(',', $arr);
     
$out .= "{{$val}}";
    }else {
     
$val = implode(',', $arr);
     
$out .= "[{$val}]";
    }
  }elseif (
is_bool($in)) {
   
$out .= $in ? 'true' : 'false';
  }elseif (
is_null($in)) {
   
$out .= 'null';
  }elseif (
is_string($in)) {
   
$out .= "\"{$_escape($in)}\"";
  }else {
   
$out .= $in;
  }
  return
"{$out}";
}
?>

have fun make money off it or what you like with you code... this is for everyone...

This isn't mentioned in the documentation for either PHP or jQuery, but if you're passing JSON data to a javascript program, make sure your program begins with:

<?php
header
('Content-Type: application/json');
?>

Notice the last json_decode does not working :) ,you need to use a variable to use the encoded data in json_decode():-
<?php
$arr
=array('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo
json_encode($arr)."<br />";
//{"a":1,"b":2,"c":3,"d":4,"e":5}

print_r (json_decode(json_encode($arr)));
//stdClass Object ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 )
echo "<br />";
$var=json_encode($arr);
print_r (json_decode($var,true));
//Array ( [a] => 1 [b] => 2 [c] => 3 [d] => 4 [e] => 5 )
echo "<br />";
print_r (json_decode(json_encode($arr)),true);//no output
?>

If your on a version of PHP before 5.2, this might help:

<?php
if (!function_exists('json_encode')) {
    function
json_encode($data) {
        switch (
$type = gettype($data)) {
            case
'NULL':
                return
'null';
            case
'boolean':
                return (
$data ? 'true' : 'false');
            case
'integer':
            case
'double':
            case
'float':
                return
$data;
            case
'string':
                return
'"' . addslashes($data) . '"';
            case
'object':
               
$data = get_object_vars($data);
            case
'array':
               
$output_index_count = 0;
               
$output_indexed = array();
               
$output_associative = array();
                foreach (
$data as $key => $value) {
                   
$output_indexed[] = json_encode($value);
                   
$output_associative[] = json_encode($key) . ':' . json_encode($value);
                    if (
$output_index_count !== NULL && $output_index_count++ !== $key) {
                       
$output_index_count = NULL;
                    }
                }
                if (
$output_index_count !== NULL) {
                    return
'[' . implode(',', $output_indexed) . ']';
                } else {
                    return
'{' . implode(',', $output_associative) . '}';
                }
            default:
                return
''; // Not supported
       
}
    }
}
?>

When you have trouble with json_encode and German umlauts. json_encode converts Strings to NULL when detecting umlauts not being UTF8encoded.

Here's another recursive UTF8 conversion function and vice-versa. The object handling might be buggy but works for me.

<?php
function array_utf8_encode_recursive($dat)
        { if (
is_string($dat)) {
            return
utf8_encode($dat);
          }
          if (
is_object($dat)) {
           
$ovs= get_object_vars($dat);
           
$new=$dat;
            foreach (
$ovs as $k =>$v)    {
               
$new->$k=array_utf8_encode_recursive($new->$k);
            }
            return
$new;
          }
         
          if (!
is_array($dat)) return $dat;
         
$ret = array();
          foreach(
$dat as $i=>$d) $ret[$i] = array_utf8_encode_recursive($d);
          return
$ret;
        }
function
array_utf8_decode_recursive($dat)
        { if (
is_string($dat)) {
            return
utf8_decode($dat);
          }
          if (
is_object($dat)) {
           
$ovs= get_object_vars($dat);
           
$new=$dat;
            foreach (
$ovs as $k =>$v)    {
               
$new->$k=array_utf8_decode_recursive($new->$k);
            }
            return
$new;
          }
         
          if (!
is_array($dat)) return $dat;
         
$ret = array();
          foreach(
$dat as $i=>$d) $ret[$i] = array_utf8_decode_recursive($d);
          return
$ret;
        }
?>

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.

<?php
$arr
= array( 'row_id' => '1', 'name' => 'George' ); // fictional db result
echo json_encode( $arr, JSON_NUMERIC_CHECK ); // {"row_id":1,"name":"George"}
?>

To save some space, at the risk of it being illegal JSON, strictly speaking:

<?php
$json
= preg_replace('/"([a-zA-Z]+[a-zA-Z0-9]*)":/', '$1:', json_encode($whatever));
?>

Another way to work with Russian characters. This procedure just handles Cyrillic characters without UTF conversion. Thanks to JsHttpRequest developers.

<?php
function php2js($a=false)
{
  if (
is_null($a)) return 'null';
  if (
$a === false) return 'false';
  if (
$a === true) return 'true';
  if (
is_scalar($a))
  {
    if (
is_float($a))
    {
     
// Always use "." for floats.
     
$a = str_replace(",", ".", strval($a));
    }

   
// All scalars are converted to strings to avoid indeterminism.
    // PHP's "1" and 1 are equal for all PHP operators, but
    // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend,
    // we should get the same result in the JS frontend (string).
    // Character replacements for JSON.
   
static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
    array(
'\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));
    return
'"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"';
  }
 
$isList = true;
  for (
$i = 0, reset($a); $i < count($a); $i++, next($a))
  {
    if (
key($a) !== $i)
    {
     
$isList = false;
      break;
    }
  }
 
$result = array();
  if (
$isList)
  {
    foreach (
$a as $v) $result[] = php2js($v);
    return
'[ ' . join(', ', $result) . ' ]';
  }
  else
  {
    foreach (
$a as $k => $v) $result[] = php2js($k).': '.php2js($v);
    return
'{ ' . join(', ', $result) . ' }';
  }
}
?>

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();

   
// loop over elements/properties
   
foreach ($var as $key => $value) {
       
// recursively convert objects
       
if (is_object($value) || is_array($value)) {
           
// but prevent cycles
           
if (!in_array($value, $references)) {
               
$result[$key] = object_to_array($value);
               
$references[] = $value;
            }
        } else {
           
// simple values are untouched
           
$result[$key] = $value;
        }
    }
    return
$result;
}

/**
* Convert a value to JSON
*
* This function returns a JSON representation of $param. It uses json_encode
* to accomplish this, but converts objects and arrays containing objects to
* associative arrays first. This way, objects that do not expose (all) their
* properties directly but only through an Iterator interface are also encoded
* correctly.
*/
function json_encode2($param) {
    if (
is_object($param) || is_array($param)) {
       
$param = object_to_array($param);
    }
    return
json_encode($param);
}

I write a function "php_json_encode"
for early version of php which support "multibyte" but doesn't support "json_encode".
<?php
 
function json_encode_string($in_str)
  {
   
mb_internal_encoding("UTF-8");
   
$convmap = array(0x80, 0xFFFF, 0, 0xFFFF);
   
$str = "";
    for(
$i=mb_strlen($in_str)-1; $i>=0; $i--)
    {
     
$mb_char = mb_substr($in_str, $i, 1);
      if(
mb_ereg("&#(\\d+);", mb_encode_numericentity($mb_char, $convmap, "UTF-8"), $match))
      {
       
$str = sprintf("\\u%04x", $match[1]) . $str;
      }
      else
      {
       
$str = $mb_char . $str;
      }
    }
    return
$str;
  }
  function
php_json_encode($arr)
  {
   
$json_str = "";
    if(
is_array($arr))
    {
     
$pure_array = true;
     
$array_length = count($arr);
      for(
$i=0;$i<$array_length;$i++)
      {
        if(! isset(
$arr[$i]))
        {
         
$pure_array = false;
          break;
        }
      }
      if(
$pure_array)
      {
       
$json_str ="[";
       
$temp = array();
        for(
$i=0;$i<$array_length;$i++)       
        {
         
$temp[] = sprintf("%s", php_json_encode($arr[$i]));
        }
       
$json_str .= implode(",",$temp);
       
$json_str .="]";
      }
      else
      {
       
$json_str ="{";
       
$temp = array();
        foreach(
$arr as $key => $value)
        {
         
$temp[] = sprintf("\"%s\":%s", $key, php_json_encode($value));
        }
       
$json_str .= implode(",",$temp);
       
$json_str .="}";
      }
    }
    else
    {
      if(
is_string($arr))
      {
       
$json_str = "\"". json_encode_string($arr) . "\"";
      }
      else if(
is_numeric($arr))
      {
       
$json_str = $arr;
      }
      else
      {
       
$json_str = "\"". json_encode_string($arr) . "\"";
      }
    }
    return
$json_str;
  }

As json_encode() won't work with character sets other than UTF-8, this expression allows to encode strings for JSON regardless of the character set:

<?php
str_replace
("\0", "\\u0000", addcslashes($string, "\t\r\n\"\\"));
?>

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.