百科狗-知识改变命运!
--

json_decode() - json函数(JavaScript对象符号)

百变鹏仔12个月前 (11-21)阅读数 48#技术干货
文章标签递归

json_decode()

(PHP 5 >= 5.2.0, PHP 7, PECL json >= 1.2.0)

对 JSON 格式的字符串进行解码

说明

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

接受一个 JSON 编码的字符串并且把它转换为 PHP 变量

参数

$json

待解码的$jsonstring格式的字符串。

这个函数仅能处理 UTF-8 编码的数据。

Note:

PHP implements a superset of JSON as specified in the original » RFC 7159.$assoc

当该参数为TRUE时,将返回array而非object。

$depth

指定递归深度。

$options

JSON_BIGINT_AS_STRING,JSON_INVALID_UTF8_IGNORE,JSON_INVALID_UTF8_SUBSTITUTE,JSON_OBJECT_AS_ARRAY,JSON_THROW_ON_ERROR组成的掩码。这些常量的行为在JSON constants页面有进一步描述。

返回值

通过恰当的 PHP 类型返回在$json中编码的数据。值true,falsenull会相应地返回TRUE,FALSENULL。如果$json无法被解码,或者编码数据深度超过了递归限制的话,将会返回NULL

更新日志

版本说明
7.3.0JSON_THROW_ON_ERROR$optionswas added.
7.2.0JSON_INVALID_UTF8_IGNORE, and JSON_INVALID_UTF8_SUBSTITUTE$optionswere added.
7.1.0 An empty JSON key("")can be encoded to the empty object property instead of using a key with value_empty_.
7.0.0 Rejected RFC 7159 incompatible number formats - top level(07, 0xff,.1,-.1)and all levels([1.],[1.e1])
7.0.0 An empty PHP string or value that after casting to string is an empty string(NULL,FALSE)results in JSON syntax error.
5.6.0 Invalid non-lowercased variants of thetrue,falseandnullliterals are no longer accepted as valid input, and will generate warnings.
5.4.0JSON_BIGINT_AS_STRING, and JSON_OBJECT_AS_ARRAY$optionswere added.
5.4.0 The$optionsparameter was added.
5.3.0 Added the optional$depth. The default recursion depth was increased from 128 to 512
5.2.3 The nesting limit was increased from 20 to 128
5.2.1 Added support for JSON decoding of basic types.

范例

json_decode()的例子

以上例程会输出:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Accessing invalid object properties

Accessing elements within an object that contain characters not permitted under PHP's naming convention(e.g. the hyphen)can be accomplished by encapsulating the element name within braces and the apostrophe.

common mistakes using json_decode()

Example #4$deptherrors

以上例程会输出:

array(1) {
  [1]=>
  array(2) {
    ["English"]=>
    array(2) {
      [0]=>
      string(3) "One"
      [1]=>
      string(7) "January"
    }
    ["French"]=>
    array(2) {
      [0]=>
      string(3) "Une"
      [1]=>
      string(7) "Janvier"
    }
  }
}
Last error: JSON_ERROR_NONE
NULL
Last error: JSON_ERROR_DEPTH

json_decode() of large integers

以上例程会输出:

object(stdClass)#1 (1) {
  ["number"]=>
  float(1.2345678901235E+19)
}
object(stdClass)#1 (1) {
  ["number"]=>
  string(20) "12345678901234567890"
}

注释

Note:

json_decode() - json函数(JavaScript对象符号)

The JSON spec is not JavaScript, but a subset of JavaScript.Note:

In the event of a failure to decode,json_last_error() can be used to determine the exact nature of the error.

参见

  • json_encode()对变量进行 JSON 编码
  • json_last_error()返回最后发生的错误
Make sure you pass in utf8 content, or json_decode may error out and just return a null value. For a particular web service I was using, I had to do the following:

Hope this helps!
The function by 1franck to allow comments works except if there is a comment at the very beginning of the file. Here's a modified version (only the regex was changed) that accounts for that. 
First of all, since JSON is not native PHP format or even native JavaScript format, everyone who wants to use JSON wisely should carefuly read official documentation. There is a link to it here, in "Introduction" section. Many questions like "it doesn't recognize my strings" and those like previous one (about zip codes) will drop if you will be attentive!
And second. I've found that there is no good, real working example of how to validate string if it is a JSON or not.
There are two ways to make this: parse input string for yourself using regular expressions or anything else, use json_decode to do it for you.
Parsing for yourself is like writing your own compiler, too difficult.
Just testing result of json_decode is not enough because you should test it with NULL, but valid JSON could be like this 'null' and it will evaluate to NULL. So you should use another function - json_last_error. It will return error code of the last encode/decode operation. If no error occured it will be JSON_ERROR_NONE. So here is the function you should use for testing:

It's so simple, that there is no need to use it and slow down your script with extra delay for function call. Just do it manualy in you code while working with input data: 
When decoding strings from the database, make sure the input was encoded with the correct charset when it was input to the database.
I was using a form to create records in the DB which had a content field that was valid JSON, but it included curly apostrophes. If the page with the form did not have 

in the head, then the data was sent to the database with the wrong encoding. Then, when json_decode tried to convert the string to an object, it failed every time.
Sometime, i need to allow comments in json file. So i wrote a small func to clean comments in a json string before decoding it: 
it seems, that some of the people are not aware, that if you are using json_decode to decode a string it HAS to be a propper json string:

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)