Testimg198
Testimg198

Reputation: 55

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.

Upvotes: 0

Views: 12421

Answers (4)

Salamander Maniacs
Salamander Maniacs

Reputation: 1

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.

Upvotes: 0

georgeawg
georgeawg

Reputation: 48968

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);

Upvotes: 0

Pheonix2105
Pheonix2105

Reputation: 1011

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);
});

Upvotes: 3

Christian Scott
Christian Scott

Reputation: 913

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" }]

Upvotes: 7

Related Questions