Reza
Reza

Reputation: 19843

How to escape double quote in JSON string

I am trying to do parse a string Hello " test containing double quote which already escaped, but I get an error

JSON.parse(`{"x":"Hello \" test "}`)

Is there anything I missed here?

enter image description here

JSON.parse(`{"x":"Hello \" test "}`)

Upvotes: 0

Views: 459

Answers (2)

dippas
dippas

Reputation: 60563

You just need to escape the backslash \, so it turns into two backslashes \\

console.log(JSON.parse('{"x":"Hello \\" test"}'))

Upvotes: 2

GMKHussain
GMKHussain

Reputation: 4681

let mydata = `{"x":"Hello \" test "}`
 
let escapeJsonFunc = function(str) {
    return str.replace(/\\/g,'\\');
};


console.log( escapeJsonFunc(mydata) )

Upvotes: -1

Related Questions