T
T
tuxx2017-08-16 17:41:10
JavaScript
tuxx, 2017-08-16 17:41:10

JSON.parse not working with apostrophe?

I want to pass some data to the page from PHP to JS
There is a code

<script>
let items = []
items.push(JSON.parse('<?= json_encode($item) ?>'))
</script>

$item contains something like
{"param1": "value1", "param2": "SYMBOL'symbol"}
C str_replace turns out like this
json_encode(str_replace("'", "\'", $item))

{"param1": "value1", "param2": "SYMBOL\\'symbol"}

those. instead of one slash, 2 are inserted at once and as a result I get an error
SyntaxError: missing ) after argument list
in the browser console . text is inserted into JSON.parse that breaks somewhere in the middle of the json string

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Koch, 2017-08-16
@tuxx

Use json encode constants :
All ' characters are encoded in \u0027. Available since PHP 5.3.0.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question