New lines and tabs in json_decode() (PHP 7)

Due to a software licensing issue, the old json module was replaced with the jsond module. You can see the discussion of this change and the attached pull request here. Now, there's not much information about the changes or about workarounds for things, but I can see that all control characters inside strings ([\0x00-\0x1F]) trigger an error. Unfortunately for you, it seems that this behavior is correct per the JSON Standard:

Insignificant whitespace is allowed before or after any token. The whitespace characters are: character tabulation (U+0009), line feed (U+000A), carriage return (U+000D), and space (U+0020). Whitespace is not allowed within any token, except that space is allowed in strings.

So, in other words, literal tabs are not allowed inside JSON strings at all; they must be \t or \u0009. So, the JSON you're consuming is in direct violation of the standard. Ideally, you should get your JSON source to return standards-compliant JSON. If that won't work, you'll have to pre-process the JSON and convert tabs inside strings to \t.


I had same problem with new lines and i cant modify the string that i received. I needed to work with it and my trick was to detect the new lines and rewrite it again, 'literaly'!:

Before:

echo json_decode($json); // error JSON_ERROR_CTRL_CHAR

After:

$json = str_replace("\r\n", '\r\n', $json); // single quotes do the trick
echo json_decode($json); // works!

Tags:

Php

Json

Php 7