JSON to JavaScript escape character Query -
i of understanding if trying stringify quotes (' , "), need escape them can't explain following results when tried same out in firebug:
1. >> json.stringify({foo: "a"a'a"}); syntaxerror: missing } after property list inference: expected since didn't escape " , '
2 >>> json.stringify({foo: "a\"a'a"}); "{"foo":"a\"a'a"}" inference/question: json string show escape character before " , why works without escaping single quote
also json throws error when try parse output string generated above js object ?
>>> json.parse("{"foo":"a\"a'a"}") syntaxerror: missing ) after argument list finally explain results below: if escape single quote once, doesn't show in output string if escape twice,
>>> json.stringify({foo: "a\"a\'a"}); "{"foo":"a\"a'a"}" >>> json.stringify({foo: "a\"a\\'a"}); "{"foo":"a\"a\\'a"}" basically trying understand when , how need escape single , double quotes when converting , json. help
edit: replies . first 2 queries clear. need escape quotes using enclose string ( in case ") , escape escape characters in string. other these 2, don't need escape other chars?
i not clear on last query. if increase escape characters before ', why shows number of escape chars in output . eg
>>> 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"}"
the format given javascript interpreter here little misleading when outputs following:
2 >>> json.stringify({foo: "a\"a'a"}); "{"foo":"a\"a'a"}" the interpreter adding double quotes on outside without doing of necessary escaping make result valid string literal, trying result of expression string contains {"foo":"a\"a'a"} (where every character there literal, including backslash). if going write javascript string literal 1 of following:
- with double quotes:
"{\"foo\":\"a\\\"a'a\"}" - with single quotes:
'{"foo":"a\\"a\'a"}'
the above strings identical, represented differently based on external quote used. should able pass either of strings json.parse , object equivalent started with.
hopefully clarify why single quote isn't escaped, shown above need escape type of quote used string literal (so escape internal double quotes if double quotes surround string, , escape internal single quotes when single quotes around string).
Comments
Post a Comment