JSON 函数
在线手册:中文 英文
PHP手册

json_decode

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

json_decode对 JSON 格式的字符串进行编码

说明

mixed json_decode ( string $json [, bool $assoc ] )

接受一个 JSON 格式的字符串并且把它转换为 PHP 变量

参数

json

待解码的 json string 格式的字符串。

assoc

当该参数为 TRUE 时,将返回 array 而非 object

返回值

Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.

范例

Example #1 json_decode() 的例子

<?php
$json 
'{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($jsontrue));

?>

以上例程会输出:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

注释

Note:

The JSON spec is not JavaScript, but a subset of JavaScript.

Note:

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

更新日志

版本 说明
5.4.0 The options parameter was added.
5.3.0 Added the optional depth. The default recursion depth was increased from 128 to 512
5.2.3 The nesting limit was increased from 20 to 128
5.2.1 Added support for JSON decoding of basic types.

参见


JSON 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 对 JSON 格式的字符串进行编码

用户评论:

aeternuslibertas at gmail dot com (14-Mar-2012 02:46)

/*since json_decode() decodes json, it MUST check if the argument passed in is json, so logically one can assume that json_decode() also functions as a json checker*/
//thus....
if(json_decode($input_json) == NULL)
{
    echo("not valid json!");
}else
{
$my_json_object = json_decode($input_json);
}

hallo at die-tilde dot de (01-Mar-2012 10:54)

You and this function saved my day. Thank you!

juanloman at hilfetech dot com (07-Jan-2012 08:38)

I found that even though json_decode() takes UTF-8 strings, it won't parse if a Byte-Order-Mark (BOM) is present.

Also, if you allow your users to edit JSON files, you end up with a mix of ASCII, ISO-8859-1, UTF-8 with and without BOM.

This function prepares a string for the JSON parser by converting it to UTF-8 and removing the BOM if present.

<?php
function prepareJSON($input) {
   
   
//This will convert ASCII/ISO-8859-1 to UTF-8.
    //Be careful with the third parameter (encoding detect list), because
    //if set wrong, some input encodings will get garbled (including UTF-8!)
   
$imput = mb_convert_encoding($input, 'UTF-8', 'ASCII,UTF-8,ISO-8859-1');
   
   
//Remove UTF-8 BOM if present, json_decode() does not like it.
   
if(substr($input, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) $input = substr($input, 3);
   
    return
$input;
}

//Usage:
$myFile = file_get_contents('somefile.json');
$myDataArr = json_decode(prepareJSON($myFile), true);

?>

sjungwirth at gmail dot com (02-Dec-2011 12:45)

My way to replace single quotes around values

<?php
$json
= <<<STR
{"key":'val',"key's":'O\\'Brian\'s', "key\"quotes\"" :  'Jimmy "the rock" Michael\'s'}
STR;
$json = preg_replace('/:\s*\'(([^\']|\\\\\')*)\'\s*([},])/e', "':'.json_encode(stripslashes('$1')).'$3'", $json);
print_r(json_decode($json, TRUE));
/**
 * Array
 * (
 *     [key] => val
 *     [key's] => O'Brian's
 *     [key"quotes"] => Jimmy "the rock" Michael's
 * )
 */
?>
combine this with previous posters way to enclose keys in double quotes and you have a loose json_decode function that can handle javascript object syntax: {key:'', ...}

rajeevroy1525 at gmail dot com (15-Nov-2011 01:38)

To test the a string, is json encoded or not. we can use the following function

<?php

function IsJsonString($str){
    try{
       
$jObject = json_decode($str);
    }catch(
Exception $e){
        return
false;
    }
    return (
is_object($jObject)) ? true : false;
}
?>

Usage  :

<?php

$jArray
= array("vars"=>array("a"=>"1", "b"=>"2"));

$jString = json_encode($jArray);
        if (
IsJsonString($jString))
        {           
        echo
"Its Json";   
        }
        else{
        echo
"It isn't Json";   
        }
?>
The above code will return "Its Json" and in case wrong json string it will return "Its isn't Json".

alexvonweiss at googlemail dot com (23-Sep-2011 04:49)

Consider that JSON can differ between int and string. So

<?php
var_dump
(json_decode('{"foo": 12}'));
// array(1) { ["foo"]=> int(12) }

var_dump(json_decode('{"foo": "12"}'));
// array(1) { ["foo"]=> string(12) }
?>

Numbers that cannot be handled by integer seems to become float casted. This can be a problem if you transfer big numbers like facebook ids over JSON. Either you avoid numbers by cast everything to string before JSON.stringify or you have to use number_format if the value bacome a float value.

<?php
// test
$x = json_decode('{"foo": 123456789012345}');
echo
sprintf('%1$f', $x->foo).PHP_EOL;
echo
sprintf('%1$u', $x->foo).PHP_EOL;
echo
sprintf('%1$s', $x->foo).PHP_EOL;
echo
strval($x->foo).PHP_EOL;
echo (string)
$x->foo.PHP_EOL;
echo
number_format($x->foo, 0, '', '').PHP_EOL;

// output
123456789012345.000000  // printf %f
2249056121              // printf %u
1.2345678901234E+14     // printf %s
1.2345678901234E+14     // strval()
1.2345678901234E+14     // cast (string)
2249056121              // cast (int)
123456789012345         // number_format()
?>

Dragos.U (05-Aug-2011 02:52)

Hmm, using eval without proper escaping of the input value  .. will not get you anything good ;)

Here is my JSON decode function, it does not decode to PHP object/array but only to an array (can be easily changed anyway).

<?php
 
function jsonDecode ($json)
  {
     
$json = str_replace(array("\\\\", "\\\""), array("&#92;", "&#34;"), $json);
     
$parts = preg_split("@(\"[^\"]*\")|([\[\]\{\},:])|\s@is", $json, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
      foreach (
$parts as $index => $part)
      {
          if (
strlen($part) == 1)
          {
              switch (
$part)
              {
                  case
"[":
                  case
"{":
                     
$parts[$index] = "array(";
                      break;
                  case
"]":
                  case
"}":
                     
$parts[$index] = ")";
                      break;
                  case
":":
                   
$parts[$index] = "=>";
                    break;   
                  case
",":
                    break;
                  default:
                      return
null;
              }
          }
          else
          {
              if ((
substr($part, 0, 1) != "\"") || (substr($part, -1, 1) != "\""))
              {
                  return
null;
              }
          }
      }
     
$json = str_replace(array("&#92;", "&#34;", "$"), array("\\\\", "\\\"", "\\$"), implode("", $parts));
      return eval(
"return $json;");
  }
?>

How it works:

it searches for the "..." (that can be a key or a value) so we need to make sure we do not take into account something like ...\"... that is not the end of the key/value but escaped value for the doublequote. That's why we first replace \\ (escaped backslash) and then we can look for a ...\"... and be sure it's not a ...\\" (the end of the key/value).

Next we split the string into chunks, any  other characters outside of the "..." only need to be []{},: (and spaces, but those we can throw away).

Next we do a little bit of checking on the data, be sure we have valid JSON and replace some of the characters on the way (so we can 'eval' as PHP code later).

Then we replace back the initial changed characters and escape $ (!!!) because we will use 'eval' with values of the array (keys and values) in double quotes.

(http://php.net/manual/en/language.types.string.php)

The function will return NULL for invalid JSON.

;)

evengard at trioptimum dot com (13-Apr-2011 04:58)

There is a problem when passing to json_decode a string with the "\" symbol. It seems to identify it as an escape character and trying to follow it. So sometimes it leads to failed parsing.

It seems that just replacing it with "\\" helps.
<?php
print_r
(json_decode(str_replace('\\', '\\\\', '{"name":"/\"}')));
?>
where /\ is the string which doesn't worked.

contacto at hardcode dot com dot ar (25-Nov-2010 09:53)

If you have a json encoded array that contains non UTF8 chars, this function will do the trick:

<?php
$array
= json_decode(safeJSON_chars($iso_8859_1_data));

function
safeJSON_chars($data) {

   
$aux = str_split($data);

    foreach(
$aux as $a) {

       
$a1 = urlencode($a);

       
$aa = explode("%", $a1);

        foreach(
$aa as $v) {

            if(
$v!="") {

                if(
hexdec($v)>127) {

               
$data = str_replace($a,"&#".hexdec($v).";",$data);

                }

            }

        }

    }

    return
$data;

}
?>

Of course it works if you want to show this inside a HTML page, so entities will be converted.
Hope this helps you as much as it helped me.

Anonymous (03-Nov-2010 09:22)

to deal with escaped dbl-quotes this is required:
if ($json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
revision is as follows:

<?php
if ( !function_exists('json_decode') ){
function
json_decode($json)
{
   
$comment = false;
   
$out = '$x=';
 
    for (
$i=0; $i<strlen($json); $i++)
    {
        if (!
$comment)
        {
            if ((
$json[$i] == '{') || ($json[$i] == '['))       $out .= ' array(';
            else if ((
$json[$i] == '}') || ($json[$i] == ']'))   $out .= ')';
            else if (
$json[$i] == ':')    $out .= '=>';
            else                        
$out .= $json[$i];         
        }
        else
$out .= $json[$i];
        if (
$json[$i] == '"' && $json[($i-1)]!="\\")    $comment = !$comment;
    }
    eval(
$out . ';');
    return
$x;
}
}
?>

Jestep (08-Sep-2010 09:26)

I had a JSON string with multiple commas in it without any quotes, which was causing the json_decode to return false.

Once the double quotes were added, everything worked out fine.

A quick:

while(strpos($contents, ',,') !== false) {
    $contents = str_replace(',,', ',"",', $contents);
}

solved the problem, and the function worked correctly. If you have tried everything and are still a FALSE return, I suggest trying the JSON validator in another post.

T erkif (10-Aug-2010 11:03)

it seems, that some of the people are not aware, that if you are using json_decode to decode a string it HAS to be a propper json string:

<?php
var_dump
(json_encode('Hello'));

var_dump(json_decode('Hello'));  // wrong
var_dump(json_decode("Hello")); // wrong
var_dump(json_decode('"Hello"')); // correct
var_dump(json_decode("'Hello'")); // wrong

result:

string(7) ""Hello""
NULL
NULL
string
(5) "Hello"
NULL

zgardner at allofe dot com (19-Jul-2010 06:23)

There seems to be a difference in the way json_decode works between 5.2.9 and 5.2.6. Trying to run json_decode on a URL in 5.2.6 will return the URL, but in 5.2.9 it will return NULL.

5.2.6
var_dump(json_decode("http://www.php.net")); // Displays string(18) "http://www.php.net"

5.2.9
var_dump(json_decode("http://www.php.net")); // Displays NULL

The servers I tested it on both had json version 1.2.1.

steveo at crecon dot com (23-Jun-2010 07:11)

I was getting an array like:
  Array
  (
      [COLUMNS] => Array
          (
              [0] => ID
              [1] => FIRST
              [2] => LAST
           )
      [DATA] => Array
          (
              [0] => Array
                    (
                          [0] => 10
                          [1] => Mary
                          [2] => Smith
                     )
               [1] => Array
                     (
                          [0] => 11
                          [1] => Joe
                          [2] => Black
                     )
               [2] => Array
                     (
                          [0] => 12
                          [1] => Tom
                          [2] => Green
                     )
               [3] => Array
       . . .

With lots more columns and data from a json_decode call to a Cold Fusion .cfc which returned a database query. This is easy to turn into a nice associative array with the following code:

<?php
 
foreach ($results['DATA'] as $rowcount => $row){
     foreach (
$row as $colcount => $col){
      
$lines[$rowcount][$results['COLUMNS'][$colcount]]=$col;
     }
  }
?>

to get:
Array
(
  [0] => Array
       (
          [ID]      => 10
          [FIRST] => Mary
          [LAST]  => Smith
        )
  [1] => Array
       (
         [ID]       => 11
         [FIRST]  => Joe
         [LAST]   => Black
       )
. . . etc.

I hope this helps someone.

majca J (06-Jun-2010 01:42)

Noted in a comment below is that this function will return NULL when given a simple string.

This is new behavior - see the result in PHP 5.2.4 :
php > var_dump(json_decode('this is a simple string'));
string(23) "this is a simple string"

in PHP 5.3.2 :
php > var_dump(json_decode('this is a simple string'));
NULL

I had several functions that relied on checking the value of a purported JSON string if it didn't decode into an object/array. If you do too, be sure to be aware of this when upgrading to PHP 5.3.

phpuser (20-May-2010 11:52)

If you keep having problems, try removing "problematic" characters from the json string:

$obj = json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string);

NemoStein (19-May-2010 06:43)

Pass you URL encoded ( urlencode($json) ), then decode it ( urldecode($_GET['json']) )...

Should do the trick...

Mitchell Simoens (06-May-2010 12:27)

In my case, I was passing simple JSON in the URL...

eg myfile.php?test=["one", "two", "three"]

but I kept getting NULL no matter what I tried. I did a simple echo of $_REQUEST["test"] and noticed that the browser added the "\" to the double-quotes. I had to prepare the data first then do the decode:

<?php
$data
= str_replace("\\", "", $_REQUEST["test"]);
$results = json_decode($data);
?>

This produced what was expected

php dot net at spam dot lublink dot net (02-Apr-2010 02:25)

If the JSON is coming from javascript watch out for undefined variables :

Javascript ( using dojo ) returns this to me sometimes :

{ "index" : [undefined] }

When I pass this to json_decode, it returns null. Make sure that you check all your javascript variables properly because this can break whatever it is you are doing.

CraigHarris at gmail dot com (19-Feb-2010 08:55)

Be aware that json_decode() will return null if you pass it a JSON encoded string.

<?php echo json_encode('Some String'); ?>
"Some String"
<?php echo json_decode(json_encode('Some String')); ?>
NULL
<?php // expected output ?>
Some String

php at hm2k.org (12-Feb-2010 12:45)

If var_dump produces NULL, you may be experiencing JSONP aka JSON with padding, here's a quick fix...

<?php

//remove padding
$body=preg_replace('/.+?({.+}).+/','$1',$body);

// now, process the JSON string
$result = json_decode($body);

var_dump($result);
?>

nix (29-Jan-2010 11:39)

Be aware, when decoding JSON strings, where an empty string is a key, this library replaces the empty string with "_empty_".

So the following code gives an unexpected result:
<?php
var_dump
(json_decode('{"":"arbitrary"}'));
?>

The result is as follows:
object(stdClass)#1 (1) {
  ["_empty_"]=>
  string(6) "arbitrary"
}

Any subsequent key named "_empty_" (or "" [the empty string] again) will overwrite the value.

yohan dot widyakencana at kreators dot com (29-Jan-2010 08:37)

When in php 5.2.3, I found that json_decode 4000000000 float value into integer value resulting int(-294967296) from var_dump function

When in php 5.3.x, php correctly returning float(4000000000)

thank you for people creating & upgrading php

Yohan W.

colin.mollenhour.com (21-Jan-2010 06:51)

For those of you wanting json_decode to be a little more lenient (more like Javascript), here is a wrapper:

<?php
function json_decode_nice($json, $assoc = FALSE){
   
$json = str_replace(array("\n","\r"),"",$json);
   
$json = preg_replace('/([{,])(\s*)([^"]+?)\s*:/','$1"$3":',$json);
    return
json_decode($json,$assoc);
}
?>

Some examples of accepted syntax:

<?php
$json
= '{a:{b:"c",d:["e","f",0]}}';
$json =
'{
   a : {
      b : "c",
      "d.e.f": "g"
   }
}'
;
?>

If your content needs to have newlines, do this:

<?php
$string
= "This
Text
Has
Newlines"
;
$json = '{withnewlines:'.json_encode($string).'}';
?>

Note: This does not fix trailing commas or single quotes.

wesgeek at gmx dot com (24-Dec-2009 06:22)

If you are having issues with magic_quotes_gpc being turned on and can't disable it use json_decode(stripslashes($json)).

benny at zami-nospam-nga dot com (16-Oct-2009 10:35)

I pulled my hair off for hours trying to get rid of strange backslashes in my incoming JSON-data in POST-pool, making it impossible to decode the incoming JSON-data.

For those of you facing the same problem:

just make sure you disable 'magic_quotes_gpc' in your php.ini and the incoming data will not be pseudo-escaped anymore. Now your incoming JSON-data should just be decoded fine.

Maybe this will help.

simonKenyonShepard at trisis dot co dot uk (14-Oct-2009 07:23)

BEWARE!

json_decode will NOT WORK if there ARE LINE BREAKS in the JSON!

Use str_replace to get rid of them.

confusioner at msn dot com (18-Jul-2009 01:33)

if you can not decode unicode characters with json_decode, use addslashes() while using json_encode. The problem comes from unicode chars starting with \ such as \u30d7

$json_data = addslashes(json_encode($unicode_string_or_array));

Nick Telford (25-Jun-2009 12:06)

In PHP <= 5.1.6 trying to decode an integer value that's > PHP_INT_MAX will result in an intger of PHP_INT_MAX.

In PHP 5.2+ decoding an integer > PHP_INT_MAX will cause a conversion to a float.

Neither behaviour is perfect, capping at PHP_INT_MAX is marginally worse, but the float conversion loses precision.

If you expect to deal with large numbers at all, let alone in JSON, ensure you're using a 64-bit system.

premiersullivan at gmail dot com (22-Jun-2009 12:14)

This function will remove trailing commas and encode in utf8, which might solve many people's problems. Someone might want to expand it to also change single quotes to double quotes, and fix other kinds of json breakage.

<?php
   
function mjson_decode($json)
    {
        return
json_decode(removeTrailingCommas(utf8_encode($json)));
    }
   
    function
removeTrailingCommas($json)
    {
       
$json=preg_replace('/,\s*([\]}])/m', '$1', $json);
        return
$json;
    }
?>

www at walidator dot info (30-May-2009 03:16)

Here's a small function to decode JSON. It might not work on all data, but it works fine on something like this:

$json_data = '{"response": {
    "Text":"Hello there"
 },
 "Details": null, "Status": 200}
 ';

===== CUt HERE :) =====

<?php
if ( !function_exists('json_decode') ){
function
json_decode($json)

   
// Author: walidator.info 2009
   
$comment = false;
   
$out = '$x=';
   
    for (
$i=0; $i<strlen($json); $i++)
    {
        if (!
$comment)
        {
            if (
$json[$i] == '{')        $out .= ' array(';
            else if (
$json[$i] == '}')    $out .= ')';
            else if (
$json[$i] == ':')    $out .= '=>';
            else                        
$out .= $json[$i];           
        }
        else
$out .= $json[$i];
        if (
$json[$i] == '"')    $comment = !$comment;
    }
    eval(
$out . ';');
    return
$x;

}
?>

Gravis (10-May-2009 03:38)

with two lines you can convert your string from JavaScript toSource() (see http://www.w3schools.com/jsref/jsref_toSource.asp) output format to JSON accepted format.  this works with subobjects too!
note: toSource() is part of JavaScript 1.3 but only implemented in Mozilla based javascript engines (not Opera/IE/Safari/Chrome).

<?php
  $str
= '({strvar:"string", number:40, boolvar:true, subobject:{substrvar:"sub string", subsubobj:{deep:"deeply nested"}, strnum:"56"}, false_val:false, false_str:"false"})'; // example javascript object toSource() output

 
$str = substr($str, 1, strlen($str) - 2); // remove outer ( and )
 
$str = preg_replace("/([a-zA-Z0-9_]+?):/" , "\"$1\":", $str); // fix variable names

 
$output = json_decode($str, true);
 
var_dump($output);
?>

var_dump output:
array(6) {
  ["strvar"]=>
  string(6) "string"
  ["number"]=>
  int(40)
  ["boolvar"]=>
  bool(true)
  ["subobject"]=>
  array(3) {
    ["substrvar"]=>
    string(10) "sub string"
    ["subsubobj"]=>
    array(1) {
      ["deep"]=>
      string(13) "deeply nested"
    }
    ["strnum"]=>
    string(2) "56"
  }
  ["false_val"]=>
  bool(false)
  ["false_str"]=>
  string(5) "false"
}

hope this saves someone some time.

jan at hooda dot de (21-Dec-2008 04:20)

This function will convert a "normal" json to an array.

<?php
  
function json_code ($json) { 

     
//remove curly brackets to beware from regex errors

     
$json = substr($json, strpos($json,'{')+1, strlen($json));
     
$json = substr($json, 0, strrpos($json,'}'));
     
$json = preg_replace('/(^|,)([\\s\\t]*)([^:]*) (([\\s\\t]*)):(([\\s\\t]*))/s', '$1"$3"$4:', trim($json));

      return
json_decode('{'.$json.'}', true);
   } 

  
$json_data = '{
      a: 1,
      b: 245,
      c with whitespaces: "test me",
      d: "function () { echo \"test\" }",
      e: 5.66
   }'


  
$jarr = json_code($json_data);
?>

Aaron Kardell (14-Nov-2008 03:39)

Make sure you pass in utf8 content, or json_decode may error out and just return a null value.  For a particular web service I was using, I had to do the following:

<?php
$contents
= file_get_contents($url);
$contents = utf8_encode($contents);
$results = json_decode($contents);
?>

Hope this helps!

steven at acko dot net (07-Oct-2008 08:49)

json_decode()'s handling of invalid JSON is very flaky, and it is very hard to reliably determine if the decoding succeeded or not. Observe the following examples, none of which contain valid JSON:

The following each returns NULL, as you might expect:

<?php
var_dump
(json_decode('['));             // unmatched bracket
var_dump(json_decode('{'));             // unmatched brace
var_dump(json_decode('{}}'));           // unmatched brace
var_dump(json_decode('{error error}')); // invalid object key/value
notation
var_dump
(json_decode('["\"]'));         // unclosed string
var_dump(json_decode('[" \x "]'));      // invalid escape code

Yet the following each returns the literal string you passed to it:

var_dump(json_decode(' [')); // unmatched bracket
var_dump(json_decode(' {')); // unmatched brace
var_dump(json_decode(' {}}')); // unmatched brace
var_dump(json_decode(' {error error}')); // invalid object key/value notation
var_dump(json_decode('"\"')); // unclosed string
var_dump(json_decode('" \x "')); // invalid escape code
?>

(this is on PHP 5.2.6)

Reported as a bug, but oddly enough, it was closed as not a bug.

[NOTE BY danbrown AT php DOT net: This was later re-evaluated and it was determined that an issue did in fact exist, and was patched by members of the Development Team.  See http://bugs.php.net/bug.php?id=45989 for details.]

jrevillini (26-Sep-2008 08:01)

When decoding strings from the database, make sure the input was encoded with the correct charset when it was input to the database.

I was using a form to create records in the DB which had a content field that was valid JSON, but it included curly apostrophes.  If the page with the form did not have

<meta http-equiv="Content-Type" content="text/html;charset=utf-8">

in the head, then the data was sent to the database with the wrong encoding.  Then, when json_decode tried to convert the string to an object, it failed every time.

soapergem at gmail dot com (23-Aug-2008 07:59)

There have been a couple of comments now alerting us to the fact that certain expressions that are valid JavaScript code are not permitted within json_decode. However, keep in mind that JSON is ***not*** JavaScript, but instead just a subset of JavaScript. As far as I can tell, this function is only allowing whatever is explicitly outlined in RFC 4627, the JSON spec.

For instance, ganswijk, the reason you can't use single quotes to enclose strings is because the spec makes no mention of allowing single quotes (and therefore they are not allowed). And the issue of adding an extra comma at the end of an array is likewise not technically permitted in strict JSON, even though it will work in JavaScript.

And xris, while the example you provided with an unenclosed string key within an object is valid JavaScript, JavaScript != JSON. If you read it closely, you'll see that the JSON spec clearly does not allow this. All JSON object keys must be enclosed in double-quotes.

Basically, if there's ever any question for what is permitted, just read the JSON spec: http://tools.ietf.org/html/rfc4627

bizarr3_2006 at yahoo dot com (06-Aug-2008 03:47)

If json_decode() failes, returns null, or returns 1, you should check the data you are sending to decode...

Check this online JSON validator... It sure helped me a lot.

http://www.jsonlint.com/

ganswijk at xs4all dot nl (07-Jul-2008 03:42)

It was quite hard to figure out the allowed Javascript formats. Some extra remarks:

json_decode() doesn't seem to allow single quotes:
<?php
print_r
(json_decode('[0,{"a":"a","b":"b"},2,3]'));  //works
print_r(json_decode("[0,{'a':'a','b':'b'},2,3]"));  //doesn't work
?>

json_decode() doesn't allow an extra comma in a list of entries:
<?php
print_r
(json_decode('[0,1 ]'));  //works
print_r(json_decode('[0,1,]'));  //doesn't work
?>

(I like to write a comma behind every entry when the entries are spread over several lines.)

json_decode() does allow linefeeds in the data!
?>

xris / a t/ basilicom.de (27-Jun-2008 04:48)

Please note: in javascript, the following is a valid object:
<?php
  
{ bar: "baz" }
?>

While PHP needs double quotes:

<?php
 
{ "bar": "baz" }
?>

phpben (16-Apr-2008 08:18)

Re requiring to escape the forward slash:

I think PHP 5.2.1 had that problem, as I remember it occurring here when I posted that comment; but now I'm on 5.2.5 it doesn't, so it has obviously been fixed. The JSON one gets from all the browsers escape the forward slashes anyway.

steve at weblite dot ca (24-Jan-2008 11:25)

For JSON support in older versions of PHP you can use the Services_JSON class, available at http://pear.php.net/pepr/pepr-proposal-show.php?id=198

<?php
if ( !function_exists('json_decode') ){
    function
json_decode($content, $assoc=false){
                require_once
'Services/JSON.php';
                if (
$assoc ){
                   
$json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        } else {
                   
$json = new Services_JSON;
                }
        return
$json->decode($content);
    }
}

if ( !
function_exists('json_encode') ){
    function
json_encode($content){
                require_once
'Services/JSON.php';
               
$json = new Services_JSON;
               
        return
$json->encode($content);
    }
}
?>

yasarbayar at gmail dot com (26-Jul-2007 10:13)

It took me a while to find the right JSON string format grabbed from mysql to be used in json_decode(). Here is what i came up with:

Bad(s) (return NULL):
{30:'13',31:'14',32:'15'}
{[30:'13',31:'14',32:'15']}
{["30":"13","31":"14","32":"15"]}

Good :
[{"30":"13","31":"14","32":"15"}]

returns:
array(1) { [0]=>  array(3) { [30]=>  string(2) "13" [31]=>  string(2) "14" [32]=>  string(2) "15" } }

hope this saves sometime..

nospam (AT) hjcms (DOT) de (22-Apr-2007 05:15)

You can't transport Objects or serialize Classes, json_* replace it bei stdClass!
<?php

$dom
= new DomDocument( '1.0', 'utf-8' );
$body = $dom->appendChild( $dom->createElement( "body" ) );
$body->appendChild( $dom->createElement( "forward", "Hallo" ) );

$JSON_STRING = json_encode(
   array(
     
"aArray" => range( "a", "z" ),
     
"bArray" => range( 1, 50 ),
     
"cArray" => range( 1, 50, 5 ),
     
"String" => "Value",
     
"stdClass" => $dom,
     
"XML" => $dom->saveXML()
   )
);

unset(
$dom );

$Search = "XML";
$MyStdClass = json_decode( $JSON_STRING );
// var_dump( "<pre>" , $MyStdClass , "</pre>" );

try {

   throw new
Exception( "$Search isn't a Instance of 'stdClass' Class by json_decode()." );

   if (
$MyStdClass->$Search instanceof $MyStdClass )
     
var_dump( "<pre>instanceof:" , $MyStdClass->$Search , "</pre>" );

} catch(
Exception $ErrorHandle ) {

   echo
$ErrorHandle->getMessage();

   if (
property_exists( $MyStdClass, $Search ) ) {
     
$dom = new DomDocument( "1.0", "utf-8" );
     
$dom->loadXML( $MyStdClass->$Search );
     
$body = $dom->getElementsByTagName( "body" )->item(0);
     
$body->appendChild( $dom->createElement( "rewind", "Nice" ) );
     
var_dump( htmlentities( $dom->saveXML(), ENT_QUOTES, 'utf-8' ) );
   }
}

?>

paul at sfdio dot com (21-Jan-2007 03:08)

I've written a javascript function to get around this functions limitations and the limitations imposed by IE's lack of native support for json serialization. Rather than converting variables to a json formatted string to transfer them to the server this function converts any javascript variable to a string serialized for use as POST or GET data.

String js2php(Mixed);

js2php({foo:true, bar:false, baz: {a:1, b:2, c:[1, 2, 3]}}));

will return:

foo=true&bar=false&baz[a]=1&baz[b]=2&baz[c][0]=1&...etc

function js2php(obj,path,new_path) {
  if (typeof(path) == 'undefined') var path=[];
  if (typeof(new_path) != 'undefined') path.push(new_path);
  var post_str = [];
  if (typeof(obj) == 'array' || typeof(obj) == 'object') {
    for (var n in obj) {
      post_str.push(js2php(obj[n],path,n));
    }
  }
  else if (typeof(obj) != 'function') {
    var base = path.shift();
    post_str.push(base + (path.length > 0 ? '[' + path.join('][') + ']' : '') + '=' + encodeURI(obj));
    path.unshift(base);
  }
  path.pop();
  return post_str.join('&');
}

Adrian Ziemkowski (13-Dec-2006 07:52)

Beware when decoding JSON from JavaScript.  Almost nobody uses quotes for object property names and none of the major browsers require it, but this function does!   {a:1} will decode as NULL, whereas the ugly {"a":1} will decode correctly.   Luckily the browsers accept the specification-style quotes as well.

giunta dot gaetano at sea-aeroportimilano dot it (04-Sep-2006 04:16)

Take care that json_decode() returns UTF8 encoded strings, whereas PHP normally works with iso-8859-1 characters.

If you expect to receive json data comprising characters outside the ascii range, be sure to use utf8_decode to convert them:

$php_vlaues = utf8_decode(json_decode($somedata))

giunta dot gaetano at sea-aeroportimilano dot it (04-Sep-2006 11:20)

Please note that this function does NOT convert back to PHP values all strings resulting from a call to json-encode.

Since the json spec says that "A JSON text is a serialized object or array", this function will return NULL when decoding any json string that does not represent either an object or an array.

To successfully encode + decode single php values such as strings, booleans, integers or floats, you will have to wrap them in an array before converting them.