将JSON解析为多个Typescript对象

贝塔罗斯

我知道关于在Typescript中解析JSON文件已经存在多个问题,但是没有一个问题对我有帮助。

我正在尝试解析json的license-checker输出的结果:

{
  "@angular/[email protected]": {
    "licenses": "MIT",
    "repository": "https://github.com/angular/angular",
    "publisher": "angular",
    "name": "@angular/core",
    "version": "10.1.4",
    "description": "Angular - the core framework",
    "licenseFile": "C:\\Users\\UC190\\workspace\\core-search-app\\node_modules\\@angular\\core\\README.md",
    "licenseText": "Angular\n=======\n\nThe sources for this package are in the main [Angular](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo.\n\nUsage information and reference details can be found in [Angular documentation](https://angular.io/docs).\n\nLicense: MIT",
    "path": "C:\\Users\\UC190\\workspace\\core-search-app\\node_modules\\@angular\\core"
  },
  "@angular/[email protected]": {
    "licenses": "MIT",
    "repository": "https://github.com/angular/angular",
    "publisher": "angular",
    "name": "@angular/forms",
    "version": "10.1.4",
    "description": "Angular - directives and services for creating forms",
    "licenseFile": "C:\\Users\\UC190\\workspace\\core-search-app\\node_modules\\@angular\\forms\\README.md",
    "licenseText": "Angular\n=======\n\nThe sources for this package are in the main [Angular](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo.\n\nUsage information and reference details can be found in [Angular documentation](https://angular.io/docs).\n\nLicense: MIT",
    "path": "C:\\Users\\UC190\\workspace\\core-search-app\\node_modules\\@angular\\forms"
  },
  ...
}

因此,我创建了一个接口来解析元素:

export interface JsonData {
  licenses: string;
  repository: string;
  publisher: string;
  name: string;
  version: string;
  description: string;
  licenseFile: string;
  licenseText: string;
  path: string;
}

但是我在如何遍历元素并将其解析为的列表上感到挣扎JsonData

马修·莱顿

TypeScript中的接口允许您描述数据结构的形状(尽管这并不是其唯一目的)。在您的情况下,数据结构是映射,在包名称上键入,带有一个对应值,即包/许可证详细信息。

考虑以下接口...

interface Package {
  licenses: string;
  repository: string;
  publisher: string;
  name: string;
  version: string;
  description: string;
  licenseFile: string;
  licenseText: string;
  path: string;
}

interface PackageMap {
  [key:string]: Package
}

您可以使用以下命令测试是否可以获取密钥及其对应的值...

const data: PackageMap = JSON.parse(json); // Assume json refers to your data structure
const keys: string[] = Object.keys(data);

keys.forEach(key => console.log(key, data[key]));

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章