【问题标题】:Parse JSON array in Typescript在 Typescript 中解析 JSON 数组
【发布时间】:2017-05-15 11:26:50
【问题描述】:

我以这种方式收到来自远程服务器的 JSON 响应:

{
  "string": [
    {
      "id": 223,
      "name": "String",
      "sug": "string",
      "description": "string",
      "jId": 530,
      "pcs": [{
        "id": 24723,
        "name": "String",
        "sug": "string"
      }]
    }, {
      "id": 247944,
      "name": "String",
      "sug": "string",
      "description": "string",
      "jlId": 531,
      "pcs": [{
        "id": 24744,
        "name": "String",
        "sug": "string"
      }]
    }
  ]
}

为了解析响应,列出“名称”和“描述”,我写了这段代码:

interface MyObj {
  name: string
  desc: string
}
let obj: MyObj = JSON.parse(data.toString());

我的问题是如何将名称和描述获取到可以显示的列表中。

【问题讨论】:

    标签: json typescript ionic2


    【解决方案1】:

    您为解析的数据提供了错误的类型。应该是这样的:

    interface MyObj {
      name: string
      description: string
    }
    
    let obj: { string: MyObj[] } = JSON.parse(data.toString());
    

    所以它不是MyObj,它是具有string 属性的对象,其中包含MyObj 的数组。你可以像这样访问这些数据:

    console.log(obj.string[0].name, obj.string[0].description);
    

    除了使用匿名类型,你也可以为它定义interface

    interface MyRootObj {
      string: MyObj[];
    }
    
    let obj: MyRootObj = JSON.parse(data.toString());
    

    【讨论】:

    • 对已经很好的答案的补充说明:不能保证JSON.parsed 数据确实符合解析后定义的接口。如果服务器突然发送其他数据,它可能不再符合它,并且通过先前预期的接口访问数据可能会导致崩溃。因此,始终建议在解析和使用数据之间验证数据。
    • 这确实是一个很好的答案,但是,如果我要插入 HTML,请问该怎么做。我使用了*ngFor = "let obj of foundData",但似乎无法获取名称列表
    • 哦,@Matthias247,请问我该如何验证数据?
    • @JendorskiLabs <p *ngFor = "let item of obj.string">{{ item.name }}</p>
    • 谢谢,我已经试过了。来自 JavaScript 控制台的错误读取 Cannot read property 'string' of undefined。我也试过<p *ngFor = "let item of obj">{{ item.string[0].name }}</p> 无济于事。
    猜你喜欢
    • 2019-06-27
    • 2020-05-02
    • 2019-07-11
    • 2018-10-02
    • 2019-02-02
    • 2017-01-23
    • 2012-04-21
    • 2018-03-08
    • 1970-01-01
    相关资源
    最近更新 更多