When trying to stringify quotes (' and "), it is necessary to escape them. However, the following results in Firebug can be puzzling:
1. >> JSON.stringify({foo: "a"a'a'});
SyntaxError: missing } after property list
Interpretation: The error occurred because I did not escape " and '
2 >>> JSON.stringify({foo: "a\"a'a"});
"{"foo":"a\"a'a"}"
Interpretation/Question: Will the JSON string also display the escape character before " and how come it functions without escaping the single quote?
Interestingly, when attempting to parse the generated output string back into a JS object, JSON throws an error:
>>> JSON.parse("{"foo":"a\"a'a"}")
SyntaxError: missing ) after argument list
To elaborate on the results further: When a single quote is escaped once, it does not appear in the output string. However, if escaped twice, it does:
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
The question arises as to when and how single and double quotes should be escaped during JSON conversion. Your assistance is appreciated.
UPDATE: Thank you for the responses. The first two questions have been clarified. It appears that only the quotes enclosing the string (in this case ") need to be escaped, along with any escape characters within the string itself. Are there any other characters that require escaping?
The final query remains unanswered. If the number of escape characters before ' is increased, why does the output show an even number of escape characters? For example,
>>> JSON.stringify({foo: "a\"a\'a"});
"{"foo":"a\"a'a"}"
>>> JSON.stringify({foo: "a\"a\\'a"});
"{"foo":"a\"a\\'a"}"
>>> JSON.stringify({foo: "a\"a\\\'a"});
"{"foo":"a\"a\\'a"}"