简体   繁体   English

如何在js中将字符串解析为数组

[英]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.我 ant 正在从服务器获取这个字符串,这是我无法控制的。 I want to display the 'k' value and when I onsole it,got我想显示“k”值,当我把它放在鞋底时,得到了

  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.但是我仍然遇到相同的意外标识符错误,任何人都请建议我帮助。Thnaks。

You're still using double quotes around x . 您仍然在x周围使用双引号。

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

Use JSON.parse to turn it into an array: 使用JSON.parse将其转换为数组:

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

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. 刚意识到您要实现的目标,如果要解析通过PHP或类似方法回显的JSON,请使用以下答案。

Example parsing JSON to a javascript array 将JSON解析为javascript数组的示例

 var jsonData = '[{"name" : "Apple"}, {"name" : "Pear"} ]'; var parsedJson = JSON.parse(jsonData); console.log(parsedJson[0]); parsedJson.forEach(function(fruit){ console.log(fruit.name); }); 

Use String.prototype.slice to strip the outer double quotes from the string returned by the server. 使用String.prototype.slice从服务器返回的字符串中去除外部双引号。

Then use JSON.parse : 然后使用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); 

I've been doing JSON with double quotes and found this solution:我一直在用双引号做 JSON 并找到了这个解决方案:

 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.通过使用\"它将取消那些双引号,直到它被解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM