Home > Back-end >  Why JSON.parse fails with this array-like string
Why JSON.parse fails with this array-like string

Time:06-01

I tried to JSON parse this

  let string = `["\"test1, "\"test2"]`;
  let array = JSON.parse(string);
  console.log(array[0]);

It's fairly simple enough but I don't understand what's error message is supposed to tell

  Uncaught SyntaxError: Unexpected token t in JSON at position 3

CodePudding user response:

you are using template string to create a string. it doesnt need a escape character for double quotes ". type this:

let string = `["test1", "test2"]`;
let array = JSON.parse(string);
console.log(array[0])

you need a escape character for " only when you are using normal string. like this:

let string = "[\"test1\", \"test2\"]";
let array = JSON.parse(string);
console.log(array[0])

im not good at english.hope useful

  • Related