Here is my string
{
'user': {
'name': 'abc',
'fx': {
'message': {
'color': 'red'
},
'user': {
'color': 'blue'
}
}
},
'timestamp': '2013-10-04T08: 10: 41+0100',
'message': 'I'mABC..',
'nanotime': '19993363098581330'
}
Here the message contains single quotation mark, which is same as the quotation used in JSON. What I do is fill up a string from user inputs such as message. So, I need to escape those kind of special scenarios which breaks the code. But other than string replace, is there any way to make them escape but still allow HTML to process them back to the correct message?
Everyone is talking about how to escape
'
in a'
-quoted string literal. There's a much bigger issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use"
.With double-quoted strings, you won't need to escape the
'
. (And if you did want a literal"
in the string, you'd use\"
.)Most of these answers either does not answer the question or is unnecessarily long in the explanation.
OK so JSON only uses double quotation marks, we get that!
I was trying to use JQuery AJAX to post JSON data to server and then later return that same information. The best solution to the posted question I found was to use:
This will escape the characters for you.
This was also suggested by Mark Amery, Great answer BTW
Hope this helps someone.
This is an issue if you include your data in an html file the following way (using ejs template engine):
if data contains a string with single quotes this will error, unless you convert
'
to\'
which is only possible by the string"\\\'"
Not pretty, but works.
The answer the direct question:
To be safe, replace the required character with \u+4-digit-hex-value
Example: If you want to escape the apostrophe ' replace with \u0027
D'Amico becomes D\u0027Amico
NICE REFERENCE: http://es5.github.io/x7.html#x7.8.4
https://mathiasbynens.be/notes/javascript-escapes
May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..
I think we all agree single quoted jsons aren't real jsons. Be that as it may, we still need to address the question of escaping " within a double quoted json string, in the absence of libraries to do so for us.
Replacing each " with a \" is NOT ENOUGH: User may enter the input: \ and parsing, again, fails (think why).
Instead, first replace each \ with \ (double backslash). Only then, replace each " with \" (backslash followed by ").