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?
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. 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.
e.g.
{ 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?
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
Yes, and quite easily too. If the following is your 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.
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:
// 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;
// }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With