Adam T Adam T - 7 months ago 8
PHP Question

How to get various values for json_last_error

I'm writing unit tests against a function inspired by Fastest way to check if a string is JSON in PHP?

For example, I've tried adding control characters to the JSON strings in order to get

json_last_error
to equal
JSON_ERROR_CTRL_CHAR
but it isn't working. It "does" give an error in JSON but it's seemingly always
JSON_ERROR_SYNTAX
. I've done some research but not sure how to make it fail in certain ways.

How might I change the JSON strings below in order to make
json_last_error
evaluate to something other than
JSON_ERROR_SYNTAX
or
JSON_ERROR_NONE
?

$json = '[{user_id":"\x0230", "username":"stack"},{"user_id":14,"username":"over"}]';
$json = '[{"user_id":"\t\\r\\n", "username":"stack"},{"user_id":14,"username":"over"}]';


Thanks in advance, Adam

Answer

I was able to get a JSON_ERROR_CTRL_CHAR like this:

$json = chr(0).'[{"user_id":"13", "username":"stack"},{"user_id":14,"username":"over"}]';

FYI, it appears to give the same error regardless of where the chr(0) is in the string, and it works for at least chr(0) - chr(31), except 9, 10, and 13.