json_decode 関数

関数 json_decode は JSON 形式の文字列を PHP 変数に変換します。関数の最初の引数は JSON 文字列、2番目は変換フラグ(オプション)、3番目は再帰の深さ(オプション)です。デフォルトでは、関数は連想配列を返します。

構文

phpjson_decode(string, [assoc = false], [depth = 512], [flags = 0]);

例

簡単な JSON 文字列を PHP オブジェクトに変換します:

php<?php
  $json = '{"a":1,"b":2,"c":3}';
  $res = json_decode($json);
  print_r($res);
?>

コード実行結果:

phpstdClass Object
(
  [a] => 1
  [b] => 2
  [c] => 3
)

例

JSON 文字列を連想配列に変換します:

php<?php
  $json = '{"a":1,"b":2,"c":3}';
  $res = json_decode($json, true);
  print_r($res);
?>

コード実行結果:

php[
  'a' => 1,
  'b' => 2,
  'c' => 3,
]

例

不正な JSON の処理:

php<?php
  $json = '{"a":1,"b":2,"c":3';
  $res = json_decode($json);
  var_dump($res);
?>

コード実行結果:

phpNULL

関連項目

  • PHP データを JSON に変換する関数 json_encode
  • PHP データを文字列に変換する関数 serialize