[英]Convert array of strings to array of objects in JSON property
我从端点返回了以下JSON
{
"response": {
"lines": [
"[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':'international'}]",
"[{'line':'3007262p7f6','type':'national'},{'line':'3007262a0s1','type':'international'}]"
]
}
}
属性lines
是一个应该包含多个数组的数组,但是,正如您所看到的, lines
是一个字符串数组。 如何使lines属性中的每个元素成为对象数组?
谢谢
您的json有几个错误(我不知道那是不是真正的json或是否经过硬编码,因此您可以检查一下)。 第一个是
'line:'3007621h7s2
应该是'line':3007621h7s2
3007621h7s2
这样的3007621h7s2
应为'3007621h7s2'
修复json后,可以使用JSON.parse()
转换字符串
var data = { "response": { "lines": [ "[{'line':'3007621h7s2', 'type': 'national'},{'line':'3007663f7s9','type':'international'}]", "[{'line':'3007262p7f6', 'type': 'national'},{'line':'3007262a0s1','type':'international'}]" ] } } data.response.lines = data.response.lines.map(a=>JSON.parse(a.replace(/'/g,'"'))) console.log( data )
将字符串转换为数组的最简单方法是对它们进行eval()
。
var obj = { "response": { "lines": [ "[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':'international'}]", "[{'line':'3007262p7f6','type':'national'},{'line':'3007262a0s1','type':'international'}]" ] } } obj.response.lines = obj.response.lines.map(line => eval(line)); console.log(obj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.