(PHP 5 >= 5.2.0, PECL json >= 1.2.0)
json_decode — JSON 文字列をデコードする
$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 の型として返します。
true、false および
null (大文字小文字を区別しません) はそれぞれ TRUE
、FALSE
そして 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($json, true));
?>
上の例の出力は以下となります。
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(
1 => 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(4, 3, -1) as $depth) {
var_dump(json_decode($json, true, $depth));
echo 'Last error: ', $json_errors[json_last_error()], PHP_EOL, PHP_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($json, false, 512, JSON_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 デコードに対応しました。 |