Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : JSON Functions : json_decode

json_decode

Decodes a JSON string (PHP 5 >= 5.2.0, PECL json:1.2.0-1.2.1)
mixed json_decode ( string json [, bool assoc] )

Example 1098. json_decode() examples

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

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

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

Code Examples / Notes » json_decode

nospam

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


phpben

whatifif at yahoo dot com said something about a bug:
"When I try to decode JSON string {"a":"

test"} into array on server-side, it fails."
That is not a valid JSON string, AFAICT. The JSON docs seem to say that '"','/' and '\' must be quoted with a '\'
$ php -r 'echo json_encode("

test");'
"

test<\/p>"
So it was your '/' character screwing it over.
You probably shouldn't blindly run stripslashes on your $input either! The only time you would is if magic_quotes_gpc is turned on and your string is coming from one of the GPC.
I inherited some PHP code which used Services_JSON. It stopped working when we upgraded PHP and started using this function. The problem was they ran html_entity_decode() over the input and &nbsp; was being turned into a character incompatible with UTF-8.


giunta dot gaetano

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


ama3

phpben at hood dot id dot au wrote:
> AFAICT. The JSON docs seem to say that '"','/' and '\' must be quoted with a '\'
At first glance, it seems that way, but if you read the RFC (4627) carefully, forward-slash (/) *may* be escaped but need not be.  Specifically, Section 2.5 defines the following:
   string = quotation-mark *char quotation-mark
   char = unescaped / ...
   unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
Forward slash falls in the second range of unescaped characters, at %x2F.
It's strange that forward-slash is permitted to be escaped but not required to be, and that it has the same meaning either way, but that's how it's written, and so shall it be.
FMI: http://www.ietf.org/rfc/rfc4627.txt


fudriot

One of the purpose of JSON is to be easy for humans to read and write. But the output of json_encode() doen't indent very nicely... a "flat" string !
This function might help to have a nice identation :)
<?php
echo indentJson(json_encode($anArray));
function indentJson($str){
$strOut = '';
$identPos = 0;
for($loop = 0;$loop<= strlen($str) ;$loop++){
$_char = substr($str,$loop,1);
//part 1
if($_char == '}' || $_char == ']'){
$strOut .= chr(13);
$identPos --;
for($ident = 0;$ident < $identPos;$ident++){
$strOut .= chr(9);
}
}
//part 2
$strOut .= $_char;
//part 3
if($_char == ',' || $_char == '{' || $_char == '['){
$strOut .= chr(13);
if($_char == '{' || $_char == '[')
$identPos ++;
for($ident = 0;$ident < $identPos;$ident++){
$strOut .= chr(9);
}
}
}
return $strOut;
?>


yasarbayar

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


paul

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('&');
}


whatifif

I think there is a bug in json_decode() method.
When I try to decode JSON string {"a":"

test"} into array on server-side, it fails.
$input='{"a":"

test"}';
$input=stripslashes($input);//ro remove slashes if any.
$output=json_decode($input, true);//it fails


,

tags should not be in the JSON string.


adrian ziemkowski

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.

Change Language


Follow Navioo On Twitter
json_decode
json_encode
eXTReMe Tracker