5

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

6
  • Why was the String created like that, exactly? Commented Jul 17, 2013 at 23:16
  • I called `JSON.stringify(array) and returned as that. Commented Jul 17, 2013 at 23:26
  • What would '['"wat"']' even mean? Commented Jul 17, 2013 at 23:35
  • That was just a placeholder for my actual string. That has double quotes surrounding a word. Commented Jul 17, 2013 at 23:37
  • 2
    how did you get the result as '["bar \\"foo\\""]'. console.log() ? Commented Jul 17, 2013 at 23:40

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.