简体   繁体   English

将字符串数组转换为JSON属性中的对象数组

[英]Convert array of strings to array of objects in JSON property

I have the following JSON returned from an endpoint 我从端点返回了以下JSON

{
    "response": {
        "lines": [
            "[{'line':'3007621h7s2','type':'national'},{'line':'3007663f7s9','type':'international'}]",
            "[{'line':'3007262p7f6','type':'national'},{'line':'3007262a0s1','type':'international'}]"
        ]
    }
}

the property lines is an array that should contain multiple arrays, however, as you can see, lines is an array of strings. 属性lines是一个应该包含多个数组的数组,但是,正如您所看到的, lines是一个字符串数组。 How can I make each element in the lines property to be an array of objects? 如何使lines属性中的每个元素成为对象数组?

Thanks 谢谢

There are a couple of errors with your json (I dont know if that is the actual json or it was hardcoded so you might check it). 您的json有几个错误(我不知道那是不是真正的json或是否经过硬编码,因此您可以检查一下)。 The first one is 第一个是

  • 'line:'3007621h7s2 should be 'line':3007621h7s2 'line:'3007621h7s2应该是'line':3007621h7s2
  • Values like 3007621h7s2 should be '3007621h7s2' 3007621h7s2这样的3007621h7s2应为'3007621h7s2'

When you fix your json, then you can use JSON.parse() to convert the string 修复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 ) 

The easiest way to convert the strings to arrays is to eval() them. 将字符串转换为数组的最简单方法是对它们进行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.

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