'How to parse a string to array in js

I have an a string like the following,

var x = "[{"k":"1"}]";
console.log(x[0].K);

I ant hange this string sine I am getting from the server.Its out of my control. I want to display the 'k' value and when I onsole it,got

  Uncaught SyntaxError: Unexpected identifier

I know,it beasuse of the 'double quotes' inside and outside of the array.

It is not even allowing me to parse it.

So,I thought

1)Replace "[  and ]" as '[  and ]'  so it becomes

 '[{"k":"1"}]'

2)Then I can parse and get the 'k' value.

var x = "[{"k":"1"}]";
console.log(x.replace(/"[/g," '[ ").replace(/"]"/g," ]'"));

But still I am getting the same unexpeted identifier error,an anyone please suggest me help.Thnaks.



Solution 1:[1]

You're still using double quotes around x.

var x = '[{"k":"1"}]';

Use JSON.parse to turn it into an array:

var array = JSON.parse(x);
console.log(array); // [{ "k": "1" }]

Solution 2:[2]

Does it need to an array of objects containing strings?

It seems you are over complicating it, try

//create a javascript object as x, set the VALUE (1) of KEY (k)
var x = {"k":"1"};
//log the objects k property
console.log(x.k);

Just realised what you are trying to achieve, go with the below answer if you're trying to parse JSON that's echo'd via PHP or something similar.

Example parsing JSON to a javascript array

var jsonData = '[{"name" : "Apple"}, {"name" : "Pear"} ]';

var parsedJson = JSON.parse(jsonData);
console.log(parsedJson[0]);

parsedJson.forEach(function(fruit){
  console.log(fruit.name);
});

Solution 3:[3]

Use String.prototype.slice to strip the outer double quotes from the string returned by the server.

Then use JSON.parse:

var x = `"[{"k":"1"}]"`
var x2 = x.slice(1,-1);
var x3 = JSON.parse(x2);
console.log(x)
console.log(x2);
console.log(x3[0]);
console.log(x3[0].k);

Solution 4:[4]

I've been doing JSON with double quotes and found this solution:

var x = "[{\"k\":\"1\"}]";
var parsedx = JSON.parse(x);
console.log(parsedx[0].k);

By using \" it will cancel those double quotes until it has been parsed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Christian Scott
Solution 2
Solution 3
Solution 4 Nick stands with Ukraine