What is the correct way to format “true” in JSON?

不羁的心 提交于 2019-12-30 08:01:44

问题


I want to give a simple true response, but according to various JSON parsers, this is not valid JSON:

true

However, PHP and Javascript act like "true" is indeed valid JSON for true, both when encoding and when decoding:

PHP-

echo json_encode( true ); // outputs: true
echo json_decode( true ); // outputs: 1
echo gettype(json_decode( true )); // outputs: boolean

jQuery-

JSON.stringify( true );   // outputs: true
jQuery.parseJSON( true ); // outputs: true
typeof jQuery.parseJSON( true ); // outputs: boolean

So what is the correct way to send a true response formatted as JSON? Are the validators all wrong?


回答1:


From the RFC :

A JSON text is a serialized object or array.

  JSON-text = object / array

Most parsers don't accept anything as root that isn't an object or an array. Only less strict parsers will accept that your JSON string just contains true.

So your options are

  • to not use JSON
  • to wrap your boolean in an object : {"result":true} or an array : [true]

Update:

The situation changed. Newer versions of the JSON specification (see this one) explicitly accept any serialized value as root of a document:

A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.

It means it's now legally acceptable to use a boolean as unique value. But of course not all libraries in use are updated, which implies using anything other than an object or an array might still be problematic.




回答2:


This will help you.

$json_ps = '{"courseList":[  
            {"course":"1", "course_data1":"Computer Systems(Networks)"},  
            {"course":"2", "course_data2":"Audio and Music Technology"},  
            {"course":"3", "course_data3":"MBA Digital Marketing"}  
        ]}';

$json_pss = json_decode($json_ps, true);

print_r($json_pss); exit;



来源:https://stackoverflow.com/questions/19435906/what-is-the-correct-way-to-format-true-in-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!