json_decode()函数是PHP中的内置函数,用于解码JSON字符串。它将JSON编码的字符串转换为PHP变量。

用法:

json_decode( $json, $assoc = FALSE, $depth = 512, $options = 0 )

参数:该函数接受上述和以下所述的四个参数:

json:它包含需要解码的JSON字符串。它仅适用于UTF-8编码的字符串。

assoc:它是一个布尔变量。如果为true,则返回的对象将转换为关联数组。

depth:它规定了用户指定的递归深度。

options:它包括JSON_OBJECT_AS_ARRAY,JSON_BIGINT_AS_STRING,JSON_THROW_ON_ERROR的位掩码。

返回值:此函数以适当的PHP类型返回编码的JSON值。如果无法解码json或编码数据比递归限制深,则它将返回NULL。

以下示例说明了PHP中json_decode()函数的用法:

示例1:

// Declare a json string

$json = '{"g":7, "e":5, "e":5, "k":11, "s":19}';

// Use json_decode() function to

// decode a string

var_dump(json_decode($json));

var_dump(json_decode($json, true));

?>

输出:

object(stdClass)#1 (4) {

["g"]=>

int(7)

["e"]=>

int(5)

["k"]=>

int(11)

["s"]=>

int(19)

}

array(4) {

["g"]=>

int(7)

["e"]=>

int(5)

["k"]=>

int(11)

["s"]=>

int(19)

}

示例2:

// Declare a json string

$json = '{"geeks": 7551119}';

// Use json_decode() function to

// decode a string

$obj = json_decode($json);

// Display the value of json object

print $obj->{'geeks'};

?>

输出:

7551119

使用json_decode()函数时的常见错误:

使用的字符串是有效的JavaScript,但不是有效的JSON。

名称和值必须用双引号引起来,不允许使用单引号。

不允许使用逗号结尾。

GitHub 加速计划 / js / json
41.72 K
6.61 K
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:7 天前 )
960b763e 2 个月前
8c391e04 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐