Home > database >  Escape json using \" in javascript
Escape json using \" in javascript

Time:04-03

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?

CodePudding user response:

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);

CodePudding user response:

Try this one

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

Hope this helps

  • Related