I have seen a few relevant answers where a specific character in JSON string from PHP is converted to javascript friendly version. With some help I have come this far :
- Javascript does not handle backslashes very well, infact these need to be replaced by double backslash.
- New line characters do not work well, either you need a carriage return or remove the symbols totally.
- double quotes in strings need escaping by 'double backslash' instead of single one.
- forward slash which appears escaped by backslash in paths does not need escaping.
example non-working json below (validated at jsonlint but fails in JSON.parse)
["string
next line \"quoted text\" and \b at path \/var\/opt "]
I needed to convert to following after replacements to make it work
["string next line \\"quoted text\\" and \\b at path /var/opt "]
The Problem
My problem is that my json in php depends on user input and I don't know what they will put up. PHP will use the standard json conversion method and have its validation.
Like the above, are there any other scenarios I should be covering, specifically unicode , other special characters etc ?
Update
My json string is a bit more complex than this example and changes dynamically, a small example is
{ "settings.conf": [ "tooltip='dynamic unicode text multiline with \ or \\ or even \" etc '", "value=the value"]}
Im doing
var jstring = <?php sanitize_json(json_encode($source_array)); ?>
JSON.parse(jstring);
and my sanitize_json function is currently doing the backslash replacement and is working, however I want to include the newline characters . Also need to ensure there are no other issues of this kind with json in js.