将JSON解析为多个Typescript对象
我知道已经有很多关于在Typescript中解析JSON文件的问题,但没有一个对我有帮助 我正在尝试解析许可证检查器输出的结果,它是一个json:将JSON解析为多个Typescript对象,json,typescript,parsing,Json,Typescript,Parsing,我知道已经有很多关于在Typescript中解析JSON文件的问题,但没有一个对我有帮助 我正在尝试解析许可证检查器输出的结果,它是一个json: { "@angular/core@10.1.4": { "licenses": "MIT", "repository": "https://github.com/angular/angular", "publish
{
"@angular/core@10.1.4": {
"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/forms@10.1.4": {
"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列表。好的,我找到了处理这个问题的方法 我可以迭代对象,该对象包含
for (const value of Object.values(data)) {
this.dataSource.data.push(this.encodeLicenseData(value));
}
并将值解析为encodeLicenseData函数中所需的值。TypeScript中的接口允许您描述数据结构的形状,但这不是它们的唯一用途。在您的情况下,数据结构是一个映射,键入包名称,并带有相应的值,即包/许可证详细信息 考虑以下接口 接口包{ 许可证:字符串; 存储库:字符串; 出版者:string; 名称:字符串; 版本:字符串; 描述:字符串; licenseFile:字符串; 许可证文本:字符串; 路径:字符串; } 接口包映射{ [键:字符串]:包 } 您可以测试您是否可以通过以下方式获取密钥及其对应的值 const data:PackageMap=JSON.parsejson;//假设json引用您的数据结构 常量键:字符串[]=Object.keysdata; keys.forEachkey=>console.logkey,数据[key];