Mikhail Tatarkov
Mikhail Tatarkov

Reputation: 7

JSON parse double quotes

I encountered a very strange error. If I run JSON.Parse('[""d""]') then I have error: "Unexpected token d in JSON at position 3"

JSON.parse('["\"d\""]')

If I run console.log(JSON.stringify(['"d"'])) then I get '[""d""]'

console.log(JSON.stringify(['"d"']))

If I run console.log(JSON.parse(JSON.stringify(['"d"']))) then I get good result [""d""]

console.log(JSON.parse(JSON.stringify(['"d"'])))

If I use eval function then I have error: "Uncaught SyntaxError: Unexpected token d in JSON at position 3"

var someJson=JSON.stringify(['"d"']);
window.eval(`JSON.parse('${someJson}')`)

How fix it?

I use some external library and there is window.eval(JSON.parse('${JSON.stringify(t)}'))). Where t - json array with strings. String can contains double quoutes. It throws exception.

I found js changed my string value when I set it.

var someJson='["\"d\""]';
console.log(someJson);

It returns '[""d""]' and when I run JSON.Parse it is incorrect JSON.

How fix it?

Upvotes: 0

Views: 2053

Answers (2)

Mikhail Tatarkov
Mikhail Tatarkov

Reputation: 7

@Quentin many thanks for idea! Result answer for me:

var someJson=JSON.stringify(['"d"']);
console.log(window.eval(`JSON.parse('${someJson.replaceAll('\\','\\\\')}')`))

Upvotes: 0

Quentin
Quentin

Reputation: 943100

JSON.parse('["\"d\""]')

\ is a special character in JS strings, so to include it in your JSON you need to escape it.

const yourString = '["\"d\""]';
const validJSON = '["\\"d\\""]'
const parsedData = JSON.parse(validJSON);

document.querySelector('#yourString').value = yourString;
document.querySelector('#validJSON').value = validJSON;
<p>Your string: <output id="yourString"></output>
<p>Valid JSON: <output id="validJSON"></output>

As a rule of thumb, embedding JSON in string literals is a waste of time and effort. You can just write the JS data structure you get from parsing the JSON.

Upvotes: 2

Related Questions