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 関数
Last updated: Fri, 06 Nov 2009

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

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

パラメータ

json

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

assoc

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

depth

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

返り値

オブジェクトを返します。あるいは、オプションのパラメータ assocTRUE の場合には、 連想配列を返します。 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 もうひとつの例

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

// エラーを定義します
$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',
);

// さまざまな深さのエラーを表示します
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 : No error has occurred

NULL
Last error : The maximum stack depth has been exceeded

注意

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

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

変更履歴

バージョン 説明
5.3.0 オプションの depth が追加されました。デフォルトの再帰の深さが 128 から 512 に増えました。
5.2.3 ネストの制限が 20 から 128 に拡張されました。

参考



json_encode> <JSON 関数
Last updated: Fri, 06 Nov 2009
 
add a note add a note User Contributed Notes
json_decode
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 関数
Last updated: Fri, 06 Nov 2009
 
 
show source | credits | sitemap | contact | advertising | mirror sites