Search code examples
javascriptjsonparsingdouble-quotes

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?


Solution

  • 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.