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 関数
[edit] Last updated: Fri, 11 May 2012

view this page in

json_decode

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

json_decodeJSON 文字列をデコードする

説明

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

JSON エンコードされた文字列を受け取り、それを PHP の変数に変換します。

パラメータ

json

デコード対象となる json 文字列。

この関数は UTF-8 でエンコードされたデータでのみ動作します。

assoc

TRUE の場合は、返されるオブジェクトが連想配列形式になります。

depth

ユーザー指定の再帰の深さ。

options

JSON デコードオプションのビットマスク。現在サポートしているオプションは JSON_BIGINT_AS_STRING のみです (デフォルトでは、大きな整数値を float に変換します)。

返り値

json でエンコードされたデータを、適切な PHP の型として返します。 truefalse および null (大文字小文字を区別しません) はそれぞれ TRUEFALSE そして NULL として返されます。 json のデコードに失敗したり エンコードされたデータが再帰制限を超えていたりした場合は NULL を返します。

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

例2 無効なオブジェクトプロパティへのアクセス

Accessing elements within an object that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

<?php

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

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

?>

例3 json_decode() でのありがちな間違い

<?php

// 以下の文字列は JavaScript としては有効ですが JSON としては無効です

// 名前と値はダブルクォートで囲む必要があります。
// シングルクォートは使えません
$bad_json "{ 'bar': 'baz' }";
json_decode($bad_json); // null

// 名前をダブルクォートで囲まなければなりません
$bad_json '{ bar: "baz" }';
json_decode($bad_json); // null

// 最後にカンマをつけてはいけません
$bad_json '{ bar: "baz", }';
json_decode($bad_json); // null

?>

例4 depth エラー

<?php
// データをエンコードします
$json json_encode(
    array(
        
=> array(
            
'English' => array(
                
'One',
                
'January'
            
),
            
'French' => array(
                
'Une',
                
'Janvier'
            
)
        )
    )
);

// エラーを定義します
$constants get_defined_constants(true);
$json_errors = array();
foreach (
$constants["json"] as $name => $value) {
    if (!
strncmp($name"JSON_ERROR_"11)) {
        
$json_errors[$value] = $name;
    }
}

// さまざまな深さのエラーを表示します
foreach (range(43, -1) as $depth) {
    
var_dump(json_decode($jsontrue$depth));
    echo 
'Last error: '$json_errors[json_last_error()], PHP_EOLPHP_EOL;
}
?>

上の例の出力は以下となります。

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: JSON_ERROR_NONE

NULL
Last error: JSON_ERROR_DEPTH

例5 json_decode() で大きな整数値を扱う例

<?php
$json 
'12345678901234567890';

var_dump(json_decode($json));
var_dump(json_decode($jsonfalse512JSON_BIGINT_AS_STRING));

?>

上の例の出力は以下となります。

float(1.2345678901235E+19)
string(20) "12345678901234567890"

注意

注意:

JSON の仕様は JavaScript そのものではなく、JavaScript のサブセットです。

注意:

デコードに失敗した場合は、json_last_error() を使用すればエラーの正確な状態を知ることができます。

変更履歴

バージョン 説明
5.4.0 options パラメータが追加されました。
5.3.0 オプションの depth が追加されました。デフォルトの再帰の深さが 128 から 512 に増えました。
5.2.3 ネストの制限が 20 から 128 に拡張されました。
5.2.1 基本型の JSON デコードに対応しました。

参考



json_encode> <JSON 関数
[edit] Last updated: Fri, 11 May 2012
 
add a note add a note User Contributed Notes json_decode
Anonymous 06-May-2012 07:08
<?php
 
include_once('json_decode.php'); // #100740 's json_decode()
 
var_dump(json_decode('"$json"'));
 
var_dump(json_decode('"$omething"'));
 
var_dump(json_decode('date("c")'));
?>

In this code, a php without built-in json_decode() prints:
  string(7) ""$json""
  string(0) ""
  string(25) "2012-05-05T00:00:00+00:00"
expecting:
  string(5) "$json"
  string(9) "$omething"
  NULL

They can be too vulnerable.  To avoid them, it should be like
below.  Since this code is still not perfect, when you have to
decode a JSON that might be invalid, you had better use a
JSON library like PEAR or Zend's, or upgrade your php.

<?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(';
          }
          elseif ((
$json[$i] == '}') || ($json[$i] == ']')) {
           
$out .= ')';
          }
          elseif (
$json[$i] == ':') {
           
$out .= '=>';
          }
          elseif (
$json[$i] == ',') {
           
$out .= ',';
          }
          elseif (
$json[$i] == '"') {
           
$out .= '"';
          }
         
/*elseif (!preg_match('/\s/', $json[$i])) {
            return null;
          }*/
       
}
        else
$out .= $json[$i] == '$' ? '\$' : $json[$i];
        if (
$json[$i] == '"' && $json[($i-1)] != '\\') $comment = !$comment;
      }
      eval(
$out. ';');
      return
$x;
    }
  }
?>
aeternuslibertas at gmail dot com 14-Mar-2012 06: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);
}
juanloman at hilfetech dot com 07-Jan-2012 12: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 01-Dec-2011 04: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 05: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 08: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 06: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 08: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 01: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 01: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 01: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 03: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 10: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 11: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 05-Jun-2010 05: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 03: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 10:43
Pass you URL encoded ( urlencode($json) ), then decode it ( urldecode($_GET['json']) )...

Should do the trick...
Mitchell Simoens 05-May-2010 04: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 06: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 12: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 11-Feb-2010 04: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 03: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 12: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 10: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 10: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 02: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 11: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 17-Jul-2009 05: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 04: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 04: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 07: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 09-May-2009 07: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 20-Dec-2008 08: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 13-Nov-2008 07: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 12: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 12: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 11: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 07: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 06-Jul-2008 07: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 08: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 12: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 03: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 02: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 09: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 20-Jan-2007 07: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 11: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 08: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 03: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.

 
show source | credits | sitemap | contact | advertising | mirror sites