我可以将字符串中的数组转换为数组吗? Java脚本

时间:2018-04-23 06:59:12

标签: javascript arrays

我的数组如下

'[{"stuff_width":200,"_id":"cPEzHYNLHhyHbtK9MJ7F","stuff_weight":400,"stuff_length":100,"image":["cPEzHYNLHhyHbtK9MJ7F_0","cPEzHYNLHhyHbtK9MJ7F_1"],"quantity":5,"stuff_type":"Cunstruction Material \\/ Cement","stuff_height":300},{"stuff_width":200,"_id":"F5OhdfGnoHpffkpR82KK","stuff_weight":300,"stuff_length":400,"image":["F5OhdfGnoHpffkpR82KK_0"],"quantity":5,"stuff_type":"Furniture \\/ Wood Items","stuff_height":400}]'

我可以删除第一个和最后一个单引号并将其用作简单数组吗?

我使用类似

的东西
courier_items.slice(1, -1);

但它给我的结果如下

{"stuff_width":2,"_id":"ubcpQhAmIiGPyrqm7OpT","stuff_weight":12,"stuff_length":1,"image":["ubcpQhAmIiGPyrqm7OpT_0","ubcpQhAmIiGPyrqm7OpT_1"],"quantity":1,"stuff_type":"Cunstruction Material \/ Cement","stuff_height":12}

它仍然像字符串一样。

我不仅要数组对象

1 个答案:

答案 0 :(得分:4)

使用JSON.parse而非slice(),因为JSON.parse将解析JSON数组并将输出作为数组输出:

var str = '[{"stuff_width":200,"_id":"cPEzHYNLHhyHbtK9MJ7F","stuff_weight":400,"stuff_length":100,"image":["cPEzHYNLHhyHbtK9MJ7F_0","cPEzHYNLHhyHbtK9MJ7F_1"],"quantity":5,"stuff_type":"Cunstruction Material \\/ Cement","stuff_height":300},{"stuff_width":200,"_id":"F5OhdfGnoHpffkpR82KK","stuff_weight":300,"stuff_length":400,"image":["F5OhdfGnoHpffkpR82KK_0"],"quantity":5,"stuff_type":"Furniture \\/ Wood Items","stuff_height":400}]';

var res = JSON.parse(str);

console.log(res);

  

使用JSON.parse()解析数据,数据成为JavaScript对象。