sheldonk
sheldonk

Reputation: 2684

Double backslash on quotes when JSON stringifying an array of strings

I'm trying to stringify a JSON object that contains a string with quotes inside of it:

array = ['bar "foo"']

However, the string is created as: '["bar \\"foo\\""]' when I was hoping for something more along the lines of '["bar \"foo\""]'. Why are there two backslashes generated? Thanks

Upvotes: 5

Views: 18264

Answers (1)

Bergi
Bergi

Reputation: 664444

Why are there two backslashes generated?

Because backslashes must be escaped by backslashes to represent one single backslash in a string literal.

The string

'["bar \\"foo\\""]'
// or
"[\"bar \\\"foo\\\"\"]"

represents the value

["bar \"foo\""]

which is JSON for an array object containing the string value bar "foo".

Probably the confusion was caused when you expected to see the value but the tool you used for that printed the string literal.

Upvotes: 13

Related Questions