PHP json_decode()函数用法详细介绍

2021年3月17日14:28:14 发表评论 854 次浏览

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

语法如下:

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

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

  • json:它包含需要解码的JSON字符串。它仅适用于UTF-8编码的字符串。
  • assoc:它是一个布尔变量。如果为true, 则返回的对象将转换为关联数组。
  • 深度:它规定了用户指定的递归深度。
  • 选项:它包含JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING, JSON_THROW_ON_ERROR的位掩码。

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

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

范例1:

<?php
  
// 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:

<?php
  
// 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。
  • 名称和值必须用双引号引起来, 不允许使用单引号。
  • 不允许使用逗号结尾。

参考: http://php.net/manual/en/function.json-decode.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: