简体   繁体   中英

json_decode is mangling string instead of returning null

One part of my app looks tests if a string can be decoded, and if so, it overwrites the variable with the decoded value:

if (json_decode($value, true)) {
    $value = json_decode($value, true);
}

On one of my servers, if I pass in the string "123-555-6789" it will parse it as valid json, but it only returns the string "123". If instead the phone number is delimited with a period character: "123.555.6789" json_decode will return "123.555". Even when it is doing this, json_last_error tell me there has been no errors.

I figured it was a bug, because the server with this issue was running older php. But then I updated it so that it is the same version as the server that is returning the correct value (NULL). It didn't fix the problem. The server with PHP Version 5.5.12 works. The server that had php 5.2 and now has 5.5.17 mangles the values. The server that gives the expected output is windows, the broken one is ubuntu. Although I don't think that would make a difference.

Is there a config setting in php.ini or something that I should turn off that would change this? something like: fundamentally_break_json = 1 ?

Actually, I believe the UBUNTU implementation is correct. json_decode is letting you know where the syntax error is occuring in the string. What you should be checking for is json_last_error(), which will return JSON_ERROR_SYNTAX to let you know the string is malformed.

If json_last_error() == JSON_ERROR_NONE, then you should be free to set your $value.

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.

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