简体   繁体   English

json_decode(“ true”)应该返回什么?

[英]What should json_decode(“true”) return?

when I try the following in PHP: 当我在PHP中尝试以下操作时:

var_dump(json_decode("123"));

var_dump(json_decode("true"));

what I expect is: 我期望的是:

NULL

NULL

but what I actually get is: 但是我实际上得到的是:

int(123)

bool(true)

Should "123" and "true" be considered valid JSON strings? 应该将“ 123”和“ true”视为有效的JSON字符串吗? Or is it a bug in the implementation of json_decode()? 还是实现json_decode()的错误?

Thanks. 谢谢。

它们不是有效的JSON文本,但是据记录json_decode函数能够处理JSON片段。

Remember that JSON is basically just javascript, and is literally just a plain-text string. 请记住,JSON基本上只是JavaScript,实际上只是纯文本字符串。 Both PHP and Javascript have true and false constants: PHP和Javascript都有truefalse常量:

php > var_dump(json_decode(true)); // php constant "true", maps to int 1
int(1)
php > var_dump(json_decode('true')); // php string / javascript constant true
bool(true)
php > var_dump(json_decode('"true"')); // json-encoded string "true"
string(4) "true"

Your "123" may be a PHP string, which leads to some oddities: 您的"123"可能是PHP字符串,这会导致一些奇怪的情况:

php > var_dump(json_encode(123));
string(3) "123"
php > var_dump(json_encode("123"));
string(5) ""123""   // not quite what you'd expect.
php > var_dump(json_encode('123'));
string(5) ""123""   // also somewhat unexpected


php > var_dump(json_decode(123));
int(123)
php > var_dump(json_decode('123'));
int(123)
php > var_dump(json_decode('"123"'));
string(3) "123"

Both results are right. 两种结果都是正确的。

string(4) "true"

as a JavaScript string should be converted back to bool(true). 因为JavaScript字符串应转换回bool(true)。 Same goes for string(3) "123". 字符串(3)“ 123”也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM