【问题标题】:Angular2: model for nested JSONAngular2:嵌套 JSON 的模型
【发布时间】:2018-01-15 19:13:53
【问题描述】:

我想在我的代码中解析一个嵌套的 json,但我在 json 建模方面遇到了困难,请帮助我获取以下 json。

{  "label": {
"Application": {
  "_default": {
    "defaultIcon": "",
    "defaultRank": 1,
    "defaultLabel": "Name",
    "defaultColor": "#ffffff",
    "displayName": "Application"
  }
}}

【问题讨论】:

  • 将您的代码添加到您要解析的位置
  • label[Application]._default[displayName] m 使用上面的代码,但 m 收到错误,即 _default 未定义
  • 您的问题无法理解。你想“建模”什么? “解析”是什么意思?你需要帮助做什么?这与 Angular 或 Angular 模板有什么关系?

标签: json angular angular2-template


【解决方案1】:

如果您想对其内容进行完整输入,则必须为 JSON 的每一级导出一个接口。

export interface DefaultApplication {
    defaultIcon: string;
    defaultRank: string;
    defaultLabel: string;
    defaultColor: string;
    displayName: string;    
}

export interface Application {
    _default: DefaultApplication;
}

export interface Label {
    Application: Application;
}

编辑:在将 JSON 用作对象之前,您应该使用 JSON.parse 解析 JSON,否则它将是 string

【讨论】:

  • 是什么让您认为这是对 OP 问题的回答?实际上,您认为 OP 的问题是什么?
  • 对我来说,这个问题可以重新格式化为“如何使用嵌套数据正确键入我的 json”。
【解决方案2】:

没有机会解析,因为你有 4 个 { 字符,只有 3 个 } 字符。 你的 JSON 应该是这样的:

{
    "label": {
        "Application": {
            "_default": {
                "defaultIcon": "",
                "defaultRank": 1,
                "defaultLabel": "Name",
                "defaultColor": "#ffffff",
                "displayName": "Application"
            }
        }
    }
}

下一次,您应该使用一些 JSON 格式化程序/验证器 f.e this 而不是编写新问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 2017-07-14
    • 2016-10-29
    • 2016-12-12
    • 2021-05-02
    • 2017-11-25
    相关资源
    最近更新 更多