JSON 関数
PHP Manual

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 の場合には、 連想配列を返します。

例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

?>

注意

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

警告

JSON エンコードされたデータのネストの深さが 127 を超えると、 この関数は FALSE を返します。

変更履歴

バージョン 説明
5.3.0 オプションの depth が追加されました。
5.2.3 ネストの制限が 20 から 128 に拡張されました。

参考


JSON 関数
PHP Manual