0

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?

2
  • where is the input coming from, why do you need to display it in json form? just escape the text (search htmlentities in js) or place it in a <pre> tag Commented Apr 2, 2022 at 19:08
  • "{"\"a\"":["\"b\"","\"c\"","\"d\""]}" Try this Commented Apr 2, 2022 at 19:11

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this one

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

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.