Reputation: 101
I have a json without escape character which I my code is unable to parse because there's no escape character. I can make it work by adding a \
before the double quotes. However, due to some constraint I am looking for a workaround and I want to know --
a. Is there any other way I can make this json work without an escape character and the content having double quotes is displayed on my application as is, or
b. do I necessarily need to have an escape character before all double quotes and there's no workaround?
"abc": {
"x1": {
"text1": "key1",
"text2": "Given "Example text" is wrong"
}
}
Thanks !!
Upvotes: 2
Views: 2796
Reputation: 1075049
Your example is invalid JSON, but I think you know that. :-)
do I necessarily need to have an escape character before all double quotes
Yes, the only way to have a "
inside a JSON string is to use an escape of some kind. Unlike JavaScript, JSON doesn't have '
-delimited strings or backtick-delimited templates that become strings (new in ES2015). There are a couple of different escape sequences you can use (\"
and \u0022
for instance), but they're still escape sequences. After all, the "
is how the JSON parser knows it's found the end of the string.
In the specific case of HTML, you could also use "
(a named character entity) if you're interpreting the string as HTML. But that doesn't change the fact you need to properly escape the string (since newlines and several other characters need escaping as well, not just "
).
My experience is that the best way to produce JSON is to produce a structure in memory and then use the facility of your environment to convert that structure to valid JSON. In JavaScript, that's JSON.stringify
; in PHP, it's json_encode
; etc. Just about any language or environment you can find has a JSON library (built-in or not) for this.
Upvotes: 5
Reputation: 1471
You SHOULD add escape char () in order to have a valid JSON. According to the specs, this is the list of special character used in JSON :
Upvotes: 1