db2791
db2791

Reputation: 1110

Stop JSON.stringify from adding escape characters

I have an object,

var obj = {};

Where I set a property

obj['prop'] = 'This is a "property"'

How can I stop

JSON.stringify(obj)

from returning

"This is a \"property\""

and instead return

"This is a "property""

Ideally, is there a way to do this where I set the property? i.e.

obj['prop'] = 'This is a "property"'

Upvotes: 1

Views: 15505

Answers (2)

KarelG
KarelG

Reputation: 5244

As explained in the comment, you cannot prevent that a double quote (") is being escaped because that character is reserved (defined in specs). What you can do is do use a work-around: use a single quote ' to quote something in a text.

If you still want to see a double quote here-after, then it's something difficult to achieve. Replacing the ' into " is not enough because there are words that use ' naturally. Like it's or don't

const obj = {};

obj['myKey'] = "first word is 'Hello World'";
obj['anotherKey'] = "second word is 'Lorum Ispum'...";

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

Upvotes: 1

Jeff Huijsmans
Jeff Huijsmans

Reputation: 1418

If you really want this, you might use something like JSON.stringify(obj).replace(/\\/g,'').

Beware: the output will NOT be a valid JSON, and dataloss can occur if you have any 'legit' backslashes in your JSON.

Upvotes: 2

Related Questions