Here is my php:
$response = array(
'errors' => $this->errors,
'orders_fulfilled' => $this->orders_fulfilled,
);
echo '<pre>$response: ' . print_r($response, true) . '</pre>';
$json = json_encode($response, JSON_HEX_APOS);
echo '<pre>$json: ' . print_r($json, true) . '</pre>';
This shows the following output:
$response: Array ( [errors] => Array ( [0] => Error text ) [orders_fulfilled] => 0 ) $json: {"errors":["Error text\n"],"orders_fulfilled":0}
QUESTION:
Why does php's json_encode()
create unescaped \n
characters out of actual newlines in the source php array, when they are not valid in the json string?
I see in this accepted answer the suggestion is to escape the source newlines, i.e. convert from \n
to \\n
. So why should PHP's json_encode()
not be doing so here? As it stands it is directly creating a json string that chokes JSON.Parse()
in javascript. For instance, try running this in console:
JSON.parse('{"errors":["Error text\n"],"orders_fulfilled":0}');
VM1628:1 Uncaught SyntaxError: Unexpected token in JSON at position 22 at JSON.parse () at :1:6
If I add a slash to escape the newline or remove it altogether, the error is gone.
Is there a flag for json_encode()
that I should be using to handle escaping of special/control characters this that I have not seen in the PHP manual?