写给愿意动手的 PHP 开发者
PHP学习网 PHP学习网
公告PHP学习网为公益性网站,致力于为广大PHP爱好者服务
JSON 与序列化 PHP PHP 5.2 json_decode

json_decode()

把 JSON 字符串解析成 PHP 变量。

json_decode(string $json, ?bool $associative = null, int $depth = 512, int $flags = 0): mixed

参数

参数类型说明
$jsonstringJSON 字符串
$associativebooltrue 返回数组,false 返回对象,省略时为 null(对象)
$depthint最大深度
$flagsintJSON_BIGINT_AS_STRING 等

返回值

mixed — 解析结果;失败返回 null。

示例

PHP
$obj = json_decode('{"a":1}');
echo $obj->a . "\n";
$arr = json_decode('{"a":1}', true);
echo $arr['a'];
输出
1
1

注意

  • 第二个参数传 true 才是数组,很多人忘了然后报「Cannot use object as array」。
  • 解析失败也返回 null,必须用 json_last_error 区分「失败」和「JSON 就是 null」。
  • 超过 PHP_INT_MAX 的数字会丢精度,用 JSON_BIGINT_AS_STRING 保留成字符串。

相关函数