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

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

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

json_encode()

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

对变量进行 JSON 编码

说明

json_encode(mixed $value[,int $options= 0[,int $depth= 512]]): string

返回字符串,包含了$value值 JSON 形式的表示。

编码受传入的$options参数影响,此外浮点值的编码依赖于serialize_precision。

参数

$value

待编码的$value,除了resource类型之外,可以为任何数据类型。

所有字符串数据的编码必须是 UTF-8。

Note:

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

由以下常量组成的二进制掩码:JSON_HEX_QUOT,JSON_HEX_TAG,JSON_HEX_AMP,JSON_HEX_APOS,JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT,JSON_UNESCAPED_SLASHES,JSON_FORCE_OBJECT,JSON_PRESERVE_ZERO_FRACTION,JSON_UNESCAPED_UNICODE,JSON_PARTIAL_OUTPUT_ON_ERROR。关于 JSON 常量详情参考JSON 常量页面。

$depth

设置最大深度。必须大于0。

返回值

成功则返回 JSON 编码的string或者在失败时返回FALSE

更新日志

版本说明
7.1.0对 Double 的值进行编码时,使用serialize_precision代替precision。
5.6.6$options参数增加常量:JSON_PRESERVE_ZERO_FRACTION
5.5.0增加$depth参数。
5.5.0增加了JSON_PARTIAL_OUTPUT_ON_ERROR选项。
5.5.0失败时返回的值从null字符串改成FALSE
5.4.0$options参数增加常量:JSON_PRETTY_PRINT,JSON_UNESCAPED_SLASHES,和JSON_UNESCAPED_UNICODE
5.3.3$options参数增加常量:JSON_NUMERIC_CHECK
5.3.0增加$options参数.

范例

json_encode()例子

以上例程会输出:

{"a":1,"b":2,"c":3,"d":4,"e":5}

json_encode()函数中$options参数的用法

以上例程会输出:

Normal: ["","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["","'bar'","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]
Empty array output as array: []
Empty array output as object: {}
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}
Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}

选项 JSON_NUMERIC_CHECK 例子

以上例程的输出类似于:

Strings representing numbers automatically turned into numbers
array(4) {
  [0]=>
  string(7) "+123123"
  [1]=>
  string(7) "-123123"
  [2]=>
  string(5) "1.2e3"
  [3]=>
  string(7) "0.00001"
}
string(28) "[123123,-123123,1200,1.0e-5]"
Strings containing improperly formatted numbers
array(2) {
  [0]=>
  string(13) "+a33123456789"
  [1]=>
  string(4) "a123"
}
string(24) "["+a33123456789","a123"]"

连续与非连续数组示例

以上例程会输出:

连续数组
array(4) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"
非连续数组
array(4) {
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
  [4]=>
  string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"
删除一个连续数组值的方式产生的非连续数组
array(3) {
  [0]=>
  string(3) "foo"
  [2]=>
  string(3) "baz"
  [3]=>
  string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"

选项 JSON_PRESERVE_ZERO_FRACTION的例子

以上例程会输出:

string(4) "12.0"
string(2) "12"

注释

Note:

如果执行失败,可以通过json_last_error()函数来获取详细错误信息。Note:

如果要编码的数组的键不是从0开始的数字,所有的键将会被当作字符串,并明确声明为 key-value 对。Note:

Like the reference JSON encoder,json_encode() will generate JSON that is a simple value(that is, neither an object nor an array)if given a string,integer,float or boolean as an input$value. While most decoders will accept these values as valid JSON, some may not, as the specification is ambiguous on this point.

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

总而言之,应该测试下 JSON decoder 能否处理json_encode()生成的数据。

参见

  • JsonSerializable
  • json_decode()对 JSON 格式的字符串进行解码
  • json_last_error()返回最后发生的错误
  • serialize()产生一个可存储的值的表示
This isn't mentioned in the documentation for either PHP or jQuery, but if you're passing JSON data to a javascript program, make sure your program begins with: 
Are you sure you want to use JSON_NUMERIC_CHECK, really really sure?
Just watch this usecase:

And then you get this JSON:
{"phone_number":33123456789}
Maybe it makes sense for PHP (as is_numeric('+33123456789') returns true), but really, casting it as an int?!
So be careful when using JSON_NUMERIC_CHECK, it may mess up with your data!
A note of caution: If you are wondering why json_encode() encodes your PHP array as a JSON object instead of a JSON array, you might want to double check your array keys because json_encode() assumes that you array is an object if your keys are not sequential.
e.g.:

As you can see, the keys are sequential; $myarray will be correctly encoded as a JSON array.

Unsetting an element will also remove the keys. json_encode() will now assume that this is an object, and will encode it as such.
SOLUTION: Use array_values() to re-index the array.
Here is a bit more on creating an iterator to get at those pesky private/protected variables: 
This is intended to be a simple readable json encode function for PHP 5.3+ (and licensed under GNU/AGPLv3 or GPLv3 like you prefer): 
I came across the "bug" where running json_encode() over a SimpleXML object was ignoring the CDATA. I ran across http://bugs.php.net/42001 and http://bugs.php.net/41976, and while I agree with the poster that the documentation should clarify gotchas like this, I was able to figure out how to workaround it.
You need to convert the SimpleXML object back into an XML string, then re-import it back into SimpleXML using the LIBXML_NOCDATA option. Once you do this, then you can use json_encode() and still get back the CDATA. 
For PHP5.3 users who want to emulate JSON_UNESCAPED_UNICODE, there is simple way to do it: 
Solution for UTF-8 Special Chars. 
If you need to force an object (ex: empty array) you can also do:
     
which acts the same as 
A note about json_encode automatically quoting numbers:
It appears that the json_encode function pays attention to the data type of the value. Let me explain what we came across:
We have found that when retrieving data from our database, there are occasions when numbers appear as strings to json_encode which results in double quotes around the values.
This can lead to problems within javascript functions expecting the values to be numeric.
This was discovered when were were retrieving fields from the database which contained serialized arrays. After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them.
The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected.
[PHP5.5 or after]
bool(false)
[PHP 5.4 or before]
string(20) "{"a":"foo","b":null}"
For anyone who would like to encode arrays into JSON, but is using PHP 4, and doesn't want to wrangle PECL around, here is a function I wrote in PHP4 to convert nested arrays into JSON.
Note that, because javascript converts JSON data into either nested named objects OR vector arrays, it's quite difficult to represent mixed PHP arrays (arrays with both numerical and associative indexes) well in JSON. This function does something funky if you pass it a mixed array -- see the comments for details.
I don't make a claim that this function is by any means complete (for example, it doesn't handle objects) so if you have any improvements, go for it. 
Please note that there was an (as of yet) undocumented change to the json_encode() function between 2 versions of PHP with respect to JSON_PRETTY_PRINT:
In version 5.4.21 and earlier, an empty array [] using JSON_PRETTY_PRINT would be rendered as 3 lines, with the 2nd one an empty (indented) line, i.e.:
  "data": [
    
  ],
In version 5.4.34 and above, an empty array [] using JSON_PRETTY_PRINT would be rendered as exactly [] at the spot where it occurs, i.e.
  "data: [],
This is not mentioned anywhere in the PHP changelist and migration documentations; neither on the json_encode documentation page.
This is very useful to know when you are parsing the JSON using regular expressions to manually insert portions of data, as is the case with my current use-case (working with JSON exports of over several gigabytes requires sub-operations and insertion of data).
This function has weird behavior regarding error reporting in PHP version 5.4 or lower. This kind of warning is raised only if you configure PHP with "display_errors=Off" (!?): "PHP Warning: json_encode(): Invalid UTF-8 sequence in argument ..."
You can reproduce this behavior:

This is considered feature - not-a-bug - by PHP devs:
https://bugs.php.net/bug.php?id=52397
https://bugs.php.net/bug.php?id=63004
Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.
Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.
In a Latin-1 encoded file, write this:

PHP = 5.5:
bool(false)
PHP 5.5 has it right of course (if encoding fails, return false) but its likely to introduce errors when updating to 5.5 because previously you could get the rest of the JSON even when one string was not in UTF8 (if this string wasn't used, you'd never notify it's nulled)
If you need pretty-printed output, but want it indented by 2 spaces instead of 4:
$json_indented_by_4 = json_encode($output, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);
$json_indented_by_2 = preg_replace('/^( +?)\\1(?=[^ ])/m', '$1', $json_indented_by_4);
Note that if you try to encode an array containing non-utf values, you'll get null values in the resulting JSON string. You can batch-encode all the elements of an array with the array_map function: 
For anyone who has run into the problem of private properties not being added, you can simply implement the IteratorAggregate interface with the getIterator() method. Add the properties you want to be included in the output into an array in the getIterator() method and return it.
Hey everyone,
In my application, I had objects that modeled database rows with a few one to many relationships, so one object may have an array of other objects.
I wanted to make the object properties private and use getters and setters, but I needed them to be serializable to json without losing the private variables. (I wanted to promote good coding practices but I needed the properties on the client side.) Because of this, I needed to encode not only the normal private properties but also properties that were arrays of other model objects. I looked for awhile with no luck, so I coded my own:
You can place these methods in each of your classes, or put them in a base class, as I've done. (But note that for this to work, the children classes must declare their properties as protected so the parent class has access)

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

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

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

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