【问题标题】:Parse a array of string objects [duplicate]解析字符串对象数组[重复]
【发布时间】:2019-08-27 01:05:08
【问题描述】:

基于下面的 JSON 数据格式,我们如何解析它,我只想获取某个键,例如我只想获取名称和优先级

[  
   "{'id': 12, 'category_name': 'BIR', 'priority': 1, 'category': 12, 'name': 'BIR FORMS'}",
   "{'id': 14, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'Pag-Ibig'}",
   "{'id': 13, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'SSS'}"
]

【问题讨论】:

  • 你的数据中没有可解析的JSON,因为里面有单引号。
  • 请显示任何试图解决您的问题的代码。

标签: javascript arrays json angularjs object


【解决方案1】:

如果您的数据中没有其他引号,您可以将单引号 ' 替换为双引号 " 以获得符合 JSON 的字符串。

然后解析字符串,获取想要的属性并映射新对象。

var strings = [  
        "{'id': 12, 'category_name': 'BIR', 'priority': 1, 'category': 12, 'name': 'BIR FORMS'}",
        "{'id': 14, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'Pag-Ibig'}",
        "{'id': 13, 'category_name': 'Contribution', 'priority': 0, 'category': 13, 'name': 'SSS'}"
    ],
    data = strings.map(s => JSON.parse(s.replace(/'/g, '"'))),
    selected = data.map(({ name, priority }) => ({ name, priority }));

console.log(selected);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    假设您有有效的 json 数据。您可以执行以下示例:

    const json = `[
       {"priority": 1, "name": "BIR FORMS"},
       {"priority": 0, "name": "Pag-Ibig"},
       {"priority": 0, "name": "SSS"}
    ]`;
    const parsedJson = JSON.parse(json);
    
    console.log(`${parsedJson[0].name}, ${parsedJson[0].priority}`);
    

    【讨论】:

      【解决方案3】:

      尝试将数据映射如下,

       let data=[
      "{'id': 12, 'category_name': 'BIR', 'priority': 1, 'category': 12, 'name': 
      'BIR FORMS'}", "{'id': 14, 'category_name': 'Contribution', 'priority': 0, 
      'category': 13, 'name': 'Pag-Ibig'}", "{'id': 13, 'category_name': 
      'Contribution', 'priority': 0, 'category': 13, 'name': 'SSS'}" ];
      let mapping= data.map((tmp)=>{
         tmp=JSON.parse(tmp)
         return {name:tmp.name,priority:tmp.priority}
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-02-12
        • 1970-01-01
        • 1970-01-01
        • 2013-03-30
        • 2018-08-31
        • 2015-08-11
        • 1970-01-01
        相关资源
        最近更新 更多