json_encode

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)

json_encode¶Ô±äÁ¿½øÐÐ JSON ±àÂë

˵Ã÷

json_encode ( mixed $value , int $options = 0 , int $depth = 512 ) : string|false

·µ»Ø×Ö·û´®£¬°üº¬ÁË value Öµ JSON ÐÎʽµÄ±íʾ¡£

±àÂëÊÜ´«ÈëµÄ options ²ÎÊýÓ°Ï죬´ËÍ⸡µãÖµµÄ±àÂëÒÀÀµÓÚ serialize_precision¡£

²ÎÊý

value

´ý±àÂëµÄ value £¬³ýÁË ×ÊÔ´(resource) ÀàÐÍÖ®Í⣬¿ÉÒÔΪÈκÎÊý¾ÝÀàÐÍ¡£

ËùÓÐ×Ö·û´®Êý¾ÝµÄ±àÂë±ØÐëÊÇ UTF-8¡£

Note:

PHP ʵÏÖÁË JSON µÄÒ»¸ö³¬¼¯£¬²Î¿¼ » RFC 7159.

options

ÓÉÒÔϳ£Á¿×é³ÉµÄ¶þ½øÖÆÑÚÂ룺 JSON_FORCE_OBJECT, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_INVALID_UTF8_IGNORE, JSON_INVALID_UTF8_SUBSTITUTE, JSON_NUMERIC_CHECK, JSON_PARTIAL_OUTPUT_ON_ERROR, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_LINE_TERMINATORS, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE, JSON_THROW_ON_ERROR¡£ ¹ØÓÚ JSON ³£Á¿ÏêÇé²Î¿¼ JSON ³£Á¿Ò³Ãæ¡£

depth

ÉèÖÃ×î´óÉî¶È¡£ ±ØÐë´óÓÚ0¡£

·µ»ØÖµ

³É¹¦Ôò·µ»Ø JSON ±àÂëµÄ string »òÕßÔÚʧ°Üʱ·µ»Ø false ¡£

¸üÐÂÈÕÖ¾

°æ±¾ ˵Ã÷
7.3.0 options ²ÎÊýÐÂÔö JSON_THROW_ON_ERROR ³£Á¿¡£
7.2.0 options ²ÎÊýÐÂÔö JSON_INVALID_UTF8_IGNORE ºÍ JSON_INVALID_UTF8_SUBSTITUTE ³£Á¿¡£
7.1.0 options ²ÎÊýÐÂÔö JSON_UNESCAPED_LINE_TERMINATORS ³£Á¿¡£
7.1.0 ¶Ô Double µÄÖµ½øÐбàÂëʱ£¬Ê¹Óà serialize_precision ´úÌæ precision¡£

·¶Àý

Example #1 json_encode() Àý×Ó

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

echo 
json_encode($arr);
?>

ÒÔÉÏÀý³Ì»áÊä³ö£º

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

Example #2 json_encode() º¯ÊýÖÐ options ²ÎÊýµÄÓ÷¨

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

ÒÔÉÏÀý³Ì»áÊä³ö£º

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 Àý×Ó

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

ÒÔÉÏÀý³ÌµÄÊä³öÀàËÆÓÚ£º

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 Á¬ÐøÓë·ÇÁ¬ÐøÊý×éʾÀý

<?php
echo "Á¬ÐøÊý×é".PHP_EOL;
$sequential = array("foo""bar""baz""blong");
var_dump(
 
$sequential,
 
json_encode($sequential)
);

echo 
PHP_EOL."·ÇÁ¬ÐøÊý×é".PHP_EOL;
$nonsequential = array(1=>"foo"2=>"bar"3=>"baz"4=>"blong");
var_dump(
 
$nonsequential,
 
json_encode($nonsequential)
);

echo 
PHP_EOL."ɾ³ýÒ»¸öÁ¬ÐøÊý×éÖµµÄ·½Ê½²úÉúµÄ·ÇÁ¬ÐøÊý×é".PHP_EOL;
unset(
$sequential[1]);
var_dump(
 
$sequential,
 
json_encode($sequential)
);
?>

ÒÔÉÏÀý³Ì»áÊä³ö£º

Á¬ÐøÊý×é
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"

·ÇÁ¬ÐøÊý×é
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"}"

ɾ³ýÒ»¸öÁ¬ÐøÊý×éÖµµÄ·½Ê½²úÉúµÄ·ÇÁ¬ÐøÊý×é
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 µÄÀý×Ó

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

ÒÔÉÏÀý³Ì»áÊä³ö£º

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

×¢ÊÍ

Note:

Èç¹ûÖ´ÐÐʧ°Ü£¬¿ÉÒÔͨ¹ý json_last_error() º¯ÊýÀ´»ñÈ¡Ïêϸ´íÎóÐÅÏ¢¡£

Note:

Èç¹ûÒª±àÂëµÄÊý×éµÄ¼ü²»ÊÇ´Ó0¿ªÊ¼µÄÊý×Ö£¬ËùÓеļü½«»á±»µ±×÷×Ö·û´®£¬²¢Ã÷È·ÉùÃ÷Ϊ key-value ¶Ô¡£

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.

×ܶøÑÔÖ®£¬Ó¦¸Ã²âÊÔÏ JSON decoder ÄÜ·ñ´¦Àí json_encode() Éú³ÉµÄÊý¾Ý¡£

²Î¼û

User Contributed Notes

mikko dot rantalainen at peda dot net 26-May-2021 08:52
Notice that <?php $json = json_encode($x, JSON_FORCE_OBJECT); ?> doesn't guarantee that $json is actually an object encoded with JSON syntax. It *only* guarantees that the output doesn't start with "[".

For example:
<?php
json_encode
("foo", JSON_FORCE_OBJECT); # "foo"
json_encode(42, JSON_FORCE_OBJECT); # 42
json_encode(false, JSON_FORCE_OBJECT); # false
json_encode("false", JSON_FORCE_OBJECT); # "false"
json_encode(10/3, JSON_FORCE_OBJECT); # 3.3333333333333335
?>
jakepucan at gmail dot com 05-Feb-2021 08:59
It's also  worth mentioning that adding charset is fine.

<?php
header
('Content-type:application/json;CHARSET=gb2312');
json_encode(['name' => 'Jake', 'country' => 'Philippines']);
msegit post pl 16-Feb-2020 05:02
Note, string keys have to be UTF-8 also! (So array_walk_recursive() isn't good way)

Consider this solution for fixing invalid UTF-8:

<?php
//$a=array('za?¨®?? g??l? ja?¨½ ZA?¨®?? G??L? JA??', 'Pai?ao'=>3, 4=>array('€€=>5, '€', 6));
$a=array(urldecode('za%BF%F3%B3%E6+g%EA%9Cl%B9+ja%9F%F1+ZA%AF%D3%A3%C6+G%CA%8CL%A5+JA%8F%D1'), urldecode('Pai%E7ao')=>3, 4=>array('€€'=>5, '€', 6)); // (for better example, independent of .php file charset)

var_dump($a);

// Normal test
echo json_encode($a, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES);
// Kind of error depends on PHP version...:
// false or '{"0":null,null:3,"4":{null:5,"0":null,"1":6}}'

if (!function_exists('urlencode_recurs')) {
function
urlencode_recurs(&$arr) {
    foreach (
$arr as $key => &$val) {
        if (
is_array($val)) {
           
urlencode_recurs($val);
           
$newarr[(is_string($key) ? urlencode($key) : $key)] = $val;    // Not $arr[...] = ..., to preserve keys/elements order
       
} else {
           
$newarr[(is_string($key) ? urlencode($key) : $key)] = (is_string($val) ? urlencode($val) : $val);    // Not $arr[...] = ..., to preserve keys/elements order
            //if (is_string($key)) unset($arr[$key]);    // Not this, to preserve keys/elements order, as above
       
}
    }
   
$arr = $newarr;
} }

if (
is_array($a)) urlencode_recurs($a);

// Fixed test
echo urldecode(json_encode($a, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES));
// '{"0":"za?¨®?? g??l? ja?¨½ ZA?¨®?? G??L? JA??","Pai?ao":3,"4":{"€€":5,"0":"€","1":6}}'
?>
avner at klido dot net 11-Nov-2019 06:59
json_encode will encode array as object if the array;s keys are not sequential starting with zero

$a = [0=>'a', 1=>'b', 2=>[0 => 'aa', 1 => 'c', 2 => 'dd']];
var_dump(json_encode($a));     //["a","b",["aa","c","dd"]]

$b = [1=>'a', 2=>'b', 3=>[0 => 'aa', 1 => 'c', 2 => 'dd']];
var_dump(jsoon_encode($b));  // {"1":"a","2":"b","3":["aa","c","dd"]}

i would expect PHP to follow the original structure or at least add a parameter to do so
jugcosta at ymail dot com 06-Nov-2019 09:31
<?php
error_reporting
(0);
ini_set('display_errors', FALSE);

$file= __DIR__ . '/utf8.csv';

    function
csvtojson($inputFile,$delimiter)
    {
  
            if ((
$handleFile = fopen($inputFile, 'r')) == false) {
                throw new
Exception("N?o foi poss¨ªvel abrir o arquivo para importar: '$file'");
            }
           
           
$dados = array();
           
            while ((
$data = fgetcsv($handleFile, 4000, $delimiter)) !== false) {
               
$data = array_map('trim', $data);

                if (! isset(
$keys)) {
                   
$keys = array_map('trim', $data);
                    continue;
                }

               
$dados[] =  array_combine($keys, $data);
               
            }
   
       
$result = json_encode($dados, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE |JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
        echo
$result;
       
       
$arquivo = "data_".date('ymdhis').".json";
       
$fp = fopen($arquivo, "a+");
       
fwrite($fp, $result);
       
       
fclose($handleFile);
       
fclose($fp);
  
    }

   
$jsonresult = csvtojson($file, ";");

?>
karsten at dambekalns dot de 01-Oct-2019 09:17
Be aware that when an error occurs, the return value might be NULL unexpectedly. Example: When running this on PHP < 7.3, you do not get back a string:

json_encode('ok', JSON_THROW_ON_ERROR, 512);

The constant not being available produces a warning and results in NULL being returned (see https://3v4l.org/ku5AH) - I'd expect false, since that's a failure, or "ok" as the encoded result. YMMV.
Anonymous 19-Mar-2019 08:35
json_encode(), besides its obvious primary use case of sending data to the client, makes for an excellent alternative to var_dump() in combination with the JSONView browser extension. This is especially true if you're unable to install XDebug on your development machine for whatever reason and can't get their pretty-printed var_dump() function to work.
Nick 04-Aug-2016 01:47
Please note that there was an (as of yet) undocumented change to the json_encode() function between 2 versions of PHP with respect to JSON_PRETTY_PRINT:

In version 5.4.21 and earlier, an empty array [] using JSON_PRETTY_PRINT would be rendered as 3 lines, with the 2nd one an empty (indented) line, i.e.:
    "data": [
       
    ],

In version 5.4.34 and above, an empty array [] using JSON_PRETTY_PRINT would be rendered as exactly [] at the spot where it occurs, i.e.
    "data: [],

This is not mentioned anywhere in the PHP changelist and migration documentations; neither on the json_encode documentation page.

This is very useful to know when you are parsing the JSON using regular expressions to manually insert portions of data, as is the case with my current use-case (working with JSON exports of over several gigabytes requires sub-operations and insertion of data).
ravenswd at gmail dot com 25-Feb-2016 01:41
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');
?>
Walter Tross 18-Nov-2015 10:02
If you need pretty-printed output, but want it indented by 2 spaces instead of 4:

$json_indented_by_4 = json_encode($output, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
$json_indented_by_2 = preg_replace('/^(  +?)\\1(?=[^ ])/m', '$1', $json_indented_by_4);
Goran 03-Apr-2015 07:00
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
ninjSPAM at informanceSPAM dot info 15-Sep-2014 09:48
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)
Ray.Paseur often uses Gmail 02-Sep-2014 06:15
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;
info at pkrules dot in 06-Nov-2013 01:24
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
?>
eep2004 at ukr dot net 13-Sep-2013 05:45
<?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: §ï§ä§Ñ §æ§å§ß§Ü§è§Ú§ñ §â§Ñ§Ò§à§ä§Ñ§Ö§ä §Ò§à§Ý§Ö§Ö §ä§à§é§ß§à §Ú §Ò§í§ã§ä§â§Ö§Ö, §é§Ö§Þ §å§Ü§Ñ§Ù§Ñ§ß§ß§Ñ§ñ §Ó§í§ê§Ö).
CertaiN 08-Jul-2013 03:51
<?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}"
guilhenfsu at gmail dot com 22-Apr-2013 08:35
Solution for UTF-8 Special Chars.

<?

$array = array('nome'=>'Pai??o','cidade'=>'S?o Paulo');

$array = array_map('htmlentities',$array);

//encode
$json = html_entity_decode(json_encode($array));

//Output: {"nome":"Pai??o","cidade":"S?o Paulo"}
echo $json;

?>
ck at ergovia dot de 28-Mar-2013 11:40
Attention when passing a plain array to json_encode and using JSON_FORCE_OBJECT. It figured out that the index-order of the resulting JSON-string depends on the system PHP is running on.

$a = array("a" , "b", "c");
echo json_encode($a, JSON_FORCE_OBJECT);

On Xampp (Windows) you get:

{"0":"a","1":"b","2":"c"}';

On a machine running debian I get:

{"2":"a","1":"b","0":"c"}';

Note that the key:value pairs are different!

Solution here was to use array_combine to create a ssociative array and then pass it to json_encode:

json_encode(array_combine(range(0, count($a) - 1), $a), JSON_FORCE_OBJECT);
webmaster_php at colnect dot com 22-Feb-2012 03:52
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);
?>
bohwaz 23-Nov-2011 05:05
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!
devilan (REMOVEIT) (at) o2 (dot) pl 15-Sep-2011 12:39
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');

}
?>
pvl dot kolensikov at gmail dot com 28-Mar-2011 08:35
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
    }]
}
Mathias Leppich 24-Feb-2011 10:29
If you need a json_encode / json_decode which is array/object/assoc-array you might want to use: http://gist.github.com/820694

<?php
$dataIn
= (object)array(
   
"assoc" => array("cow"=>"moo"),
   
"object" => (object)array("cat"=>"miao"),
);
/*
== IN
object(stdClass)#2 (2) {
  ["assoc"]=>
  array(1) {
    ["cow"]=>
    string(3) "moo"
  }
  ["object"]=>
  object(stdClass)#1 (1) {
    ["cat"]=>
    string(4) "miao"
  }
}

== JSON
{"assoc":{"_PHP_ASSOC":{"cow":"moo"}},"object":{"cat":"miao"}}

== OUT
object(stdClass)#4 (2) {
  ["assoc"]=>
  array(1) {
    ["cow"]=>
    string(3) "moo"
  }
  ["object"]=>
  object(stdClass)#7 (1) {
    ["cat"]=>
    string(4) "miao"
  }
}
*/
?>
bohwaz 26-Jan-2011 02:00
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;
}

?>
dan at elearnapp dot com 13-Jan-2011 12:01
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); ?>
nicolas dot baptiste at gmail dot com 18-Aug-2010 08:49
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.
mic dot sumner at gmail dot com 02-Jul-2010 06:39
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!
ryan at ryanparman dot com 27-Mar-2010 01:36
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));
?>
5hunter5 at mail dot ru 17-Feb-2010 03:03
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...
garydavis at gmail dot com 14-Jan-2010 07:38
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
?>
simoncpu was here 20-Oct-2009 02:18
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.
Istratov Vadim 09-Jun-2009 11:54
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.
Sam Barnum 20-Apr-2009 11:01
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);
?>
andyrusterholz at g-m-a-i-l dot c-o-m 27-Mar-2009 11:17
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;
}

?>
aangel at spam dot com 07-Feb-2009 05:50
Here is a bit more on creating an iterator to get at those pesky private/protected variables:

<?php
  
class Kit implements IteratorAggregate {

    public function
__construct($var) {
        if (
is_object($var)) {
           
// if passed an object, we are cloning
          
$this->kitID = $var->kitID;
          
$this->kitName = $var->kitName;
           foreach (
$var->productArray as $key => $value) {
              
$this->productArray[$key] = (array)$value;
           }
        }
    }
   ...
   
// Create an iterator because private/protected vars can't
    // be seen by json_encode().
   
public function getIterator() {
       
$iArray['kitID'] = $this->kitID;
       
$iArray['kitName'] = $this->kitName;
       
$iArray['productArray'] = (array)$this->productArray;
        return new
ArrayIterator($iArray);
    }
}
?>

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

        $newKit
= new Kit(json_decode($t));
?>
Garrett 22-Oct-2008 11:17
A note about json_encode automatically quoting numbers:

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.
spam.goes.in.here AT gmail.com 08-Aug-2008 11:05
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.
umbrae at gmail dot com 10-Jan-2008 10:21
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;
}
?>
dennispopel(at)gmail.com 26-Aug-2007 10:43
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
PHP8ÖÐÎÄÊÖ²á ÓÉ Õ¾³¤ÔÚÏß ÕûÀí °æȨ¹éPHPÎĵµ×éËùÓÐ