我从端点返回了以下JSON
{
"response": {
"lines": [
"[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':'international'}]",
"[{'line':'3007262p7f6','type':'national'},{'line':'3007262a0s1','type':'international'}]"
]
}
}
属性lines
是一个数组,应包含多个数组,但是,如您所见,lines
是一个字符串数组。如何使lines属性中的每个元素成为对象数组?
谢谢
答案 0 :(得分:1)
您的json有几个错误(我不知道这是不是实际的json或是否经过硬编码,因此您可以检查一下)。第一个是
'line:'3007621h7s2
应该是'line':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
)
答案 1 :(得分:1)
将字符串转换为数组的最简单方法是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);