I have a string that is returned from an API. For some reason one of the values within the JSON returned is null54 which breaks the json_decode and therefore doesn't allow me to access it as an array correctly.
Example String: {"ttl": null54 "card_id": "np"}.DPTQIg.eeQ-wZYaH8ptEofYGZM0E8ICZDQ
You will see this has null54
as a value for ttl
. This prevents the below PHP from working. If I manually remove 54
then the php works fine. How can I remove any numbers that may be with null
to prevent the php from not working? I cannot guarantee that it will always be 54 either.
Working PHP:
$string = '{"ttl": null, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg';
$string = explode('}', $string);
$json = json_decode($string[0] .'}');
echo $json->card_id;
Non-Working PHP:
$string = '{"ttl": null54, "card_id": "np"}.DPSXmw.VApKpbKiEnEoRgwWblgt-nuewFg';
$string = explode('}', $string);
$json = json_decode($string[0] .'}');
echo $json->card_id;
This is clearly a bug with the API, and @chris-forrence is correct in that you should raise a bug with the API maintainer if possible... That being said, you'll probably have to work around the issue, at least for a while.
I think the easiest way to do this would be using a regexp find and replace. This can be handled with the preg_replace()
function and would look something like:
$string = preg_replace('/null[0-9]+/', 'null', $string)
Here the first argument is a regex, that matches the string 'null' and any number of digits following it.