简体   繁体   English

如何在 TypeScript 中输入 JSON 导入

[英]How to type a JSON import in TypeScript

Basically I want to type an imported JSON so I could inspect it easily.基本上我想输入一个导入的 JSON 以便我可以轻松地检查它。 This is what Ive tried:这是我试过的:

// typings.d.ts

type NetWorkReport = {
  log: {
    version: string
    creator: any
    pages: any[]
    entries: Request[]
  }
}

declare module "*.json" {
  const value: NetWorkReport;
  export default value;
}

And my code where I import the file:以及我导入文件的代码:

// index.ts

import * as networkCapture from './networkCapture.json';

console.log(networkCapture.log) // ERROR: Property 'log' does not exist on type '{}'

My JSON is huge (Its actually an export from Chrome DevTools > Network > Export HAR... ).我的 JSON 很大(它实际上是从Chrome DevTools > Network > Export HAR... )。 The first lines are:第一行是:

{
  "log": {
    "version": "1.2",
    "creator": {
      "name": "WebInspector",
      "version": "537.36"
    },
    "pages": [
      {
        "startedDateTime": "2020-03-11T12:21:37.400Z",
        "id": "page_1",
        "title": "https://somewebpage.com",
        "pageTimings": {
          "onContentLoad": 1946.7949999962002,
          "onLoad": 3050.905000010971
        }
      }
    ],

...

What Im doing wrong?我做错了什么?

I have also import the json file on .ts page.我还在 .ts 页面上导入了 json 文件。

import like.进口之类的。

import * as countries from '../../../environments/countries.json';

and than get the data in constructor like this.而不是像这样在构造函数中获取数据。

let countriesList: any = [];
countriesList = countries;

So you can do like this to get your Json data.所以你可以这样做来获取你的 Json 数据。

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

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