Last active
August 29, 2015 14:12
-
-
Save mmcc/3910ce76bf56d58b1781 to your computer and use it in GitHub Desktop.
Stringifying strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}"}' | |
// (╯°□°)╯︵ ┻━┻ |
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
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"}"}'
// (╯°□°)╯︵ ┻━┻