在 Typescript 中解析 JSON 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41408471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:45:40  来源:igfitidea点击:

Parse JSON array in Typescript

jsontypescriptionic2

提问by Jendorski Labs

i have a JSON response from remote server in this way:

我以这种方式从远程服务器收到 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"
      }]
    }
  ]
}

In order to parse the response, to list out the "name" & "description", i have written this code out:

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

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

My question is how do i obtain the name and description into a list that can be displayed.

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

回答by Yaroslav Admin

You gave incorrect type to your parsed data. Should be something like this:

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

interface MyObj {
  name: string
  description: string
}

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

So it's not MyObj, it's object with property stringcontaining array of MyObj. Than you can access this data like this:

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

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

Instead of using anonymous type, you can also define interfacefor it:

除了使用匿名类型,您还可以interface为其定义:

interface MyRootObj {
  string: MyObj[];
}

let obj: MyRootObj = JSON.parse(data.toString());