简体   繁体   English

Typescript:从大 JSON 生成密钥,无需手动匹配类型

[英]Typescript: Generating keys from large JSON without manually matching types

Is there a way to parse large JSON files in Typescript, and to access the values associated with its various keys, without having to manually create interfaces that represent the key/value pairs I'm expecting?有没有办法解析 Typescript 中的大型 JSON 文件,并访问与其各种键关联的值,而无需手动创建表示我期望的键/值对的接口?

In the past I have only had to deal with small-ish JSON files and extract only a select few of keys so I created interfaces that I parsed the JSON on.在过去,我只需要处理小的 JSON 文件并且只提取 select 几个键,所以我创建了我解析 JSON 的接口。 However, I'm now dealing with files that have a lot of key/value pairs and I don't believe manually translating the JSON into typed interfaces to be the fastest solution.但是,我现在正在处理具有大量键/值对的文件,并且我认为手动将 JSON 转换为类型化接口不是最快的解决方案。

eg例如

{ organisation : {
     name : "Example Organisation"
     paymentTerms: "Some text"
     registrationNumber :"1234"
     ...
  history : [{...}]
  ...
  //another 100 or so lines
}

Is there a way I can automatically type, in the above example, the organisation, history, etc. items and their nested keys so that when I parse the JSON file I can simply access the keys and their values without manually creating an expected interface?在上面的示例中,有没有一种方法可以自动键入组织、历史等项目及其嵌套键,以便在解析 JSON 文件时,我可以简单地访问键及其值,而无需手动创建预期的界面?

I have read a few solutions about 'json streaming' but I'm not sure if that's overkill since my files aren't really data dumps我已经阅读了一些关于“json streaming”的解决方案,但我不确定这是否过大,因为我的文件并不是真正的数据转储

Yes, and quite easily too.是的,也很容易。 If the following is your JSON如果下面是你的JSON

// file.json

{
  "organisation": {
    "name": "Example Organisation",
    "paymentTerms": "Some text",
    "registrationNumber": "1234"
  },
  "history": [{}]
}

Then you can do a namespace import ( import * as X from 'abc' ) to import the whole JSON file in one go.然后你可以做一个命名空间导入( import * as X from 'abc' )将整个 JSON 文件导入一个 go。

After it has been imported you can use it and create derived types from it just like you could with any other static JS object. Here are some examples:导入后,您可以使用它并从中创建派生类型,就像使用任何其他 static JS object 一样。以下是一些示例:

// index.ts

import * as FileJson from './file.json';

type FileJsonType = typeof FileJson;
// type FileJsonType = {
//     organisation: {
//         name: string;
//         paymentTerms: string;
//         registrationNumber: string;
//     };
//     history: {}[];
// }

type FileJsonKeys = keyof FileJsonType; // "organisation" | "history"

type Organisation = FileJsonType['organisation'];
// type Organisation = {
//     name: string;
//     paymentTerms: string;
//     registrationNumber: string;
// }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM