Skip to content

Instantly share code, notes, and snippets.

@mmcc
Last active August 29, 2015 14:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mmcc/3910ce76bf56d58b1781 to your computer and use it in GitHub Desktop.
Stringifying strings
var blah = { foo: "bar", neat: "true", something: "{\"cool\": \"not\"}"}
// { foo: 'bar',
// neat: 'true',
// something: '{"cool": "not"}' }
// So far, so good.
var stringified = JSON.stringify(blah)
// '{"foo":"bar","neat":"true","something":"{\\"cool\\": \\"not\\"}"}'
// Not what we wanted, but this is reasonable and expected.
// SO...what if we just started out as a string and escaped the contained JSON?
var ugh = '{ "foo": "bar", "neat": "true", "something": "{\"cool\": \"not\"}"}'
// '{ "foo": "bar", "neat": "true", "something": "{"cool": "not"}"}'
// (╯°□°)╯︵ ┻━┻
@barisbalic
Copy link

var blah = { foo: "bar", neat: "true" }
blah['something'] = JSON.parse( "{"cool": "not"}"})

// { foo: 'bar',
// neat: 'true',
// something: '{"cool": "not"}' }
// So far, so good.

var stringified = JSON.stringify(blah)
// '{"foo":"bar","neat":"true","something":"{"cool": "not"}"}'
// Not what we wanted, but this is reasonable and expected.

// SO...what if we just started out as a string and escaped the contained JSON?
var ugh = '{ "foo": "bar", "neat": "true", "something": "{"cool": "not"}"}'
// '{ "foo": "bar", "neat": "true", "something": "{"cool": "not"}"}'
// (╯°□°)╯︵ ┻━┻

@corasaurus-hex
Copy link

You need to escape the backslashes in ugh, too. They will be evaluated as escaping the "s while the string is being interpreted and because that is not needed they will be lost. You need them to survive so that the JSON is well-formed.

var ugh = '{ "foo": "bar", "neat": "true", "something": "{\\"cool\\": \\"not\\"}"}'
// '{ "foo": "bar", "neat": "true", "something": "{\\"cool\\": \\"not\\"}"}'
JSON.parse(ugh)
// { foo: 'bar',
//  neat: 'true',
//  something: '{"cool": "not"}' }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment