when I try the following in 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? Or is it a bug in the implementation of json_decode()?
Thanks.
它们不是有效的JSON文本,但是据记录json_decode
函数能够处理JSON片段。
Remember that JSON is basically just javascript, and is literally just a plain-text string. Both PHP and Javascript have true
and false
constants:
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:
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). Same goes for string(3) "123".
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.