downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

json_encode> <JSON Functions
Last updated: Fri, 12 Mar 2010

view this page in

json_decode

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

json_decodeDecodes a JSON string

Description

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 ]] )

Takes a JSON encoded string and converts it into a PHP variable.

Parameters

json

The json string being decoded.

assoc

When TRUE, returned object s will be converted into associative array s.

depth

User specified recursion depth.

Return Values

Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.

Examples

Example #1 json_decode() examples

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

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

?>

The above example will output:

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)
}

Example #2 Another example

<?php

$json 
'{"foo-bar": 12345}';

$obj json_decode($json);
print 
$obj->{'foo-bar'}; // 12345

?>

Example #3 common mistakes using json_decode()

<?php

// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes
// single quotes are not valid 
$bad_json "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// the name must be enclosed in double quotes
$bad_json '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed
$bad_json '{ bar: "baz", }';
json_decode($bad_json); // null

?>

Example #4 depth errors

<?php
// Encode the data.
$json json_encode(
    array(
        
=> array(
            
'English' => array(
                
'One',
                
'January'
            
),
            
'French' => array(
                
'Une',
                
'Janvier'
            
)
        )
    )
);

// Define the errors.
$json_errors = array(
    
JSON_ERROR_NONE => 'No error has occurred',
    
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
    
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
    
JSON_ERROR_SYNTAX => 'Syntax error',
);

// Show the errors for different depths.
foreach(range(43, -1) as $depth) {
    
var_dump(json_decode($jsonTrue$depth));
    echo 
'Last error : '$json_errors[json_last_error()], PHP_EOLPHP_EOL;
    }
?>

The above example will output:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error : No error has occurred

NULL
Last error : The maximum stack depth has been exceeded

Notes

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.

Changelog

Version Description
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

See Also



json_encode> <JSON Functions
Last updated: Fri, 12 Mar 2010
 
add a note add a note User Contributed Notes
json_decode
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 09: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 06: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 12: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 11: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
21-Jun-2009 11: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 02: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 02: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 07: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 07: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 06: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 02: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 02: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 03: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 07: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 09: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 04: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 03: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 10: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.

json_encode> <JSON Functions
Last updated: Fri, 12 Mar 2010
 
 
show source | credits | sitemap | contact | advertising | mirror sites