Alexander Mills
Alexander Mills

Reputation: 100010

What rule determines escaping in JSON

Say I have this:

const v = {
  val: ' bad \\"  string"'
};

console.log(JSON.stringify(v));

JSON.stringify knows to add an escape \ backslash so that the output looks like:

{"val":" bad \\\"  string\""}

what rule is being followed here? How does the stringify routine know to add the 3rd backslash?

Upvotes: 0

Views: 278

Answers (1)

Tomalak
Tomalak

Reputation: 338208

what rule is being followed here? How does the stringify routine know to add the 3rd backslash?

This JavaScript string literal

' bad \\"  string"'

represents this string

 bad \"  string"

when converted to JSON, the double quotes " and the backslashes \ must be escaped, so

" bad \\\"  string\""

follows naturally. Straight from json.org:

JSON string syntax diagram

Upvotes: 2

Related Questions