admin管理员组

文章数量:1025334

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?

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?

Share Improve this question edited May 23, 2017 at 11:45 CommunityBot 11 silver badge asked Dec 15, 2016 at 15:31 ajmedwayajmedway 1,49214 silver badges29 bronze badges 3
  • This is not a Shopify issue, strictly a question about php's json_encode and usage in conjunction with JSON.parse – ajmedway Commented Dec 15, 2016 at 15:39
  • Question do you parse the $json in the html (print $json)? Because then the linebreak is noticed by the browser! Or how do you test the JSON.parse('{"errors":["Sh line ? – JustOnUnderMillions Commented Dec 15, 2016 at 15:42
  • If you can't control outputs of error, just add addslashes manually in your $response – br3t Commented Dec 15, 2016 at 16:01
Add a ment  | 

1 Answer 1

Reset to default 6

The output of json_encode is fine.

The problem is that when you try to convert it to a JavaScript string literal by wrapping it with ', the \n gets parsed as a new line in the JS string.

When you try to parse that string as JSON, it has a real new line in it.

To convert to a JavaScript string, you also have to escape any special characters in it.

Since JSON is (more-or-less) a subset of JavaScript, json_encode will do that:

var json = <?php json_encode(json_encode($foo)); ?>;
var obj = JSON.parse(json);
console.log(obj);

… but that's a silly approach.

Just skip the bit where you treat it as JSON and just treat it as JavaScript.

var obj = <?php json_encode($foo); ?>;
console.log(obj);

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?

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?

Share Improve this question edited May 23, 2017 at 11:45 CommunityBot 11 silver badge asked Dec 15, 2016 at 15:31 ajmedwayajmedway 1,49214 silver badges29 bronze badges 3
  • This is not a Shopify issue, strictly a question about php's json_encode and usage in conjunction with JSON.parse – ajmedway Commented Dec 15, 2016 at 15:39
  • Question do you parse the $json in the html (print $json)? Because then the linebreak is noticed by the browser! Or how do you test the JSON.parse('{"errors":["Sh line ? – JustOnUnderMillions Commented Dec 15, 2016 at 15:42
  • If you can't control outputs of error, just add addslashes manually in your $response – br3t Commented Dec 15, 2016 at 16:01
Add a ment  | 

1 Answer 1

Reset to default 6

The output of json_encode is fine.

The problem is that when you try to convert it to a JavaScript string literal by wrapping it with ', the \n gets parsed as a new line in the JS string.

When you try to parse that string as JSON, it has a real new line in it.

To convert to a JavaScript string, you also have to escape any special characters in it.

Since JSON is (more-or-less) a subset of JavaScript, json_encode will do that:

var json = <?php json_encode(json_encode($foo)); ?>;
var obj = JSON.parse(json);
console.log(obj);

… but that's a silly approach.

Just skip the bit where you treat it as JSON and just treat it as JavaScript.

var obj = <?php json_encode($foo); ?>;
console.log(obj);

本文标签: javascriptphp jsonencode creating unescaped new line operatorsStack Overflow