简体   繁体   English

如何在 Typescript 中访问 JSON object?

[英]How to access JSON object in Typescript?

I have that JSON 'media' object that looks like this:我有看起来像这样的 JSON 'media' object:

const media = [{
    "0": {
        "small": "",
        "large": ""
    }
}];

I have to type it this way:我必须这样输入:

export interface Media {
    0: {
        large: string
        medium: string
        small: string,
        type: string
    }
}

in order to be able to access it, via element[0].small .为了能够通过element[0].small访问它。

All the JSON objects I am working with are like the following, with an index equals to 0 , which is not very useful but I can't change it.我正在使用的所有 JSON 对象如下所示,索引等于0 ,这不是很有用,但我无法更改。

Is there any way I can access my properties just by doing element.small ?有什么方法可以通过element.small访问我的属性吗?

You can transform your JSON objects and use them in the simplified form:您可以转换您的 JSON 对象并以简化形式使用它们:

const clean = (elem) => elem[0];

You can also gain typescript's type support when doing this, eg you can define with a generic:执行此操作时,您还可以获得 typescript 的类型支持,例如,您可以使用泛型定义:

export interface Raw<T> {
    0: T
}
const transform = <T>(raw: Raw<T>): T => raw[0];

That way you can type your JSON input via Raw<The_Interface_I_Want> ;这样你就可以通过Raw<The_Interface_I_Want>输入你的 JSON 输入;

You can then define interfaces just for the relevant information:然后,您可以仅为相关信息定义接口:

export interface Media {
    large: string
    medium: string
    small: string,
    type: string
}

And then you can use it like so:然后你可以像这样使用它:

const rawMedia: Raw<Media> = {
    0: {
        "large": "large",
        "small": "small",
        "medium": "medium",
        "type": "type"
    }
};

const media: Media = transform<Media>(rawMedia);

Benefit of doing it this way is that you always have type inference and gain autoccompletion this way.这样做的好处是您始终可以进行类型推断并以这种方式获得自动补全。 In theory, you could also customize the transformation the way you need it.理论上,您还可以根据需要自定义转换。

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

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