当前位置: 首页> 函数类别大全> json_decode

json_decode

对 JSON 格式的字符串进行解码
名称:json_decode
分类:JSON
所属语言:php
一句话介绍:解码 JSON 字符串。

json_decode函数

适用PHP版本

PHP 5.2.0及以上版本

函数说明

json_decode() 函数用于将一个 JSON 格式的字符串转换为 PHP 变量。

函数语法

json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0): mixed

参数

  • $json (string): 要解码的 JSON 格式的字符串。
  • $assoc (bool) (可选): 如果设置为 true,返回结果将转换为关联数组(默认为 false)。
  • $depth (int) (可选): 最大递归深度,默认值为 512。
  • $options (int) (可选): 控制解码的选项,可以用来改变解析行为,默认为 0。

返回值

返回 PHP 变量,具体类型由解码的 JSON 数据决定。如果解析失败,返回 NULL。

示例

假设你有一个 JSON 字符串,你想将它解码为 PHP 数组:

示例代码的说明

  $jsonString = '{"name": "John", "age": 30, "city": "New York"}';
  $decodedArray = json_decode($jsonString, true);
  var_dump($decodedArray);
  

上述代码将 JSON 字符串解码为 PHP 关联数组,输出结果将会是:

  array(3) {
    ["name"] => string(4) "John"
    ["age"] => int(30)
    ["city"] => string(8) "New York"
  }
  
同类函数