Felizitas
Felizitas

Reputation: 1

Escape json using \" in javascript

I have this input {"a":["b","c","d"]}

For whatever reason, I need output like this "{\"a\":[\"b\",\"c\",\"d\"]}"

Instead of this (using JSON.stringify()) '{"a":["b","c","d"]}'

I know I can write some replacements or something. Is there any native Javascript method to do this?

Upvotes: 0

Views: 885

Answers (2)

pilchard
pilchard

Reputation: 12956

The problem with using a custom replace is that you risk making the string invalid JSON. Instead you can simply stringify it twice, which will properly escape all special characters such that it can be reliably parsed back to a valid javascript object.

const input = { 'a': ['A string with "quotes"', "c", "d"] };

const string = JSON.stringify(JSON.stringify(input));
console.log(string);

const parsed = JSON.parse(JSON.parse(string));
console.log(parsed);

Upvotes: 1

user8115627
user8115627

Reputation: 118

Try this one

const a = {"a":["b","c","d"]}
const output = JSON.stringify(a).replaceAll('"', '\\"')
console.log(output)

Hope this helps

Upvotes: 0

Related Questions