在JS中将字符串转换为数组

时间:2018-08-29 05:49:16

标签: javascript

在我的项目中,我有一个如下用例:

我有一个如下所示的响应数组,

(4) [{…}, {…}, {…}, {…}]
0:{header: 0, name: "Name", field: "Id"}
1:{header: 3, name: "LastName", field: "Agreement__c"}
2:{header: 3, name: "LastName", field: "Amount__c"}
3:{header: 3, name: "LastName", field: "BIC__c"}
length:4
上面的

我通过使用将上面的数组转换为String,

JSON.stringify(responseArray)并将其存储在字符串字段中。

之后,我想对该字段的值进行一些动态处理。因此,当我从字段中获取值时,如下所示,

[{"header":0,"name":"Name","field":"Id"}, 
{"header":3,"name":"LastName","field":"Agreement__c"}, 
{"header":3,"name":"LastName","field":"Amount__c"}, 
{"header":3,"name":"LastName","field":"BIC__c"}]

任何人都可以帮助我将上述字符串响应转换为Javascript中的数组,如下所示,

index 0 -> {"header":0,"name":"Name","field":"Id"}
index 1 -> {"header":3,"name":"LastName","field":"Agreement"}

我已经尝试过使用split函数,但无法满足确切的需求。

5 个答案:

答案 0 :(得分:4)

在字符串的开头和结尾放置方括号,然后调用JSON.parse

 $ node

 > const text = `{"header":0,"name":"Name","field":"Id"}, 
    {"header":3,"name":"LastName","field":"Agreement"}, 
    {"header":3,"name":"LastName","field":"Amount"}, 
    {"header":3,"name":"LastName","field":"BIC"}`

 > JSON.parse(`[${text}]`)
 [ { header: 0, name: 'Name', field: 'Id' },
   { header: 3, name: 'LastName', field: 'Agreement' },
   { header: 3, name: 'LastName', field: 'Amount' },
   { header: 3, name: 'LastName', field: 'BIC' } ]

答案 1 :(得分:2)

您可以使用以下代码示例在字符串的开头先添加"[",然后在字符串的末尾添加"]",这样您的字符串将被很好地格式化为JSON数组,因此解析起来非常容易使用内置功能 JSON.parse

 a = '['+'{"header":0,"name":"Name","field":"Id"}, {"header":3,"name":"LastName","field":"Agreement"}, {"header":3,"name":"LastName","field":"Amount"}, {"header":3,"name":"LastName","field":"BIC"}'+"]"

 var myarray = JSON.parse(a);

答案 2 :(得分:1)

是的,JSON.parse是真正简单的答案。

答案 3 :(得分:0)

您只需要一些基本的字符串操作,顺便说一句,我将您的字符串更改为有效的语法

var str="{\"header\":0,\"name\":\"Name\",\"field\":\"Id\"},{\"header\":3,\"name\":\"LastName\",\"field\":\"Agreement\"},{\"header\":3,\"name\":\"LastName\",\"field\":\"Amount\"},{\"header\":3,\"name\":\"LastName\",\"field\":\"BIC\"}";

str=str.replace(/},{/g,"}|{");
var arr = str.split("|");
var json = [];
for(i=0; i<arr.length; i++){
json.push(JSON.parse(arr[i]));
}

//console.log(json);
console.log(json[0]);
console.log(json[1]);

答案 4 :(得分:0)

尝试

    var textstr = '[{"header":0,"name":"Name","field":"Id"},{"header":3,"name":"LastName","field":"Agreement"}, {"header":3,"name":"LastName","field":"Amount"}, {"header":3,"name":"LastName","field":"BIC"}]';
    var textstr2 = JSON.parse(textstr);
    console.log(textstr2)