1

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

Community
  • 1
  • 1
Adam T
  • 675
  • 8
  • 22

1 Answers1

1

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.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
  • 1
    Also found [this answer](http://stackoverflow.com/a/24543526/2734189) that gets a `JSON_ERROR_STATE_MISMATCH`. – Don't Panic Apr 18 '16 at 20:19
  • @dont-panic, I tried both your answer (to get the ctrl char) and the comment link for `state mismatch` error and both worked great. In addition, I was able to remove the numeric case in the switch block!. Cheers, and thanks much. – Adam T Apr 18 '16 at 20:29
  • Have tried to find an example to trip the `JSON_ERROR_UTF8` case but so far the one on the manual page didn't seem to work – Adam T Apr 18 '16 at 21:29
  • Got it working (the check for bad UTF-8) by taking a string that had UTF-8 and passing it through `utf_decode` function. When it got checked for its JSON correctness... it failed due to invalid UTF. For possible future use... this should fail to be valid JSON: `$json = '[{"condition":"très agréable","explanation":"†gráficos\xB1\x31"}]'; $json = utf8_decode($json);` – Adam T Apr 18 '16 at 22:22