【问题标题】:Accessing items inside a JSON [Using Typescript/Angular2]访问 JSON 中的项目 [使用 Typescript/Angular2]
【发布时间】:2018-05-12 10:52:25
【问题描述】:

我的 JSON 是什么样子的:

{
  "reportSections": [
    {
      "name": "...",
      "display": true,
      "nav": false,
      "reportGroups": {
        "reports": [
          {
            "name": "...",
            "url": "reportLibrary.tableau",
            "nav": true,
            "params": {
              "reportName": "clientRelationshipReport",
              "reportTitle": "Client Relationship Report",
              "reportUrl": "...",
              "reportHeight": "4030px"
            },
            "filters": "clientName,brokerName,entity,budgetClass,practice,office"
          }
        ]
      }
    }
  ]
}

组件中的我的 HTML 文件模板

<li *ngFor = "let sectionName of reportNavJSONMain.reportSections">
     <span> {{ sectionName.name }} </span>
     <ul>
       <li *ngFor="let report of sectionName.reportGroups.reports">
          <a *ngIf="report.nav"> {{report.name}} </a>
       </li>
      </ul>
 </li>

我的 component.ts 方法是什么样的:

//<irrelevant code> 
....
getReports(): any {
    new Promise((resolve,reject)=>{
      resolve(
        this.reportNavService.getJSONReportMain()
      )
    }).then((data)=>{
      // console.dir(JSON.parse(JSON.stringify(data)));
      this.reportNavJSONMain = JSON.stringify(data);
      console.dir(this.reportNavJSONMain )
    })
  }
  ...
  //<irrelevant code>

我的服务代码:

//.... 
public getJSONReportMain(): Promise<any> {
    return this.http.get('...')
      .toPromise()
      .then((response: Response)=>{
        //console.log(JSON.stringify(response.json()))
        this.reportNavJSON = JSON.stringify(response.json());
        return this.reportNavJSON;
      }).catch((error: Response)=>{
        return Observable.throw('Error');
      });
  }
  // ....

在 component.ts 文件中,我已经将 this.reportNavJSONMain 初始化为一个对象(我也将它初始化为一个对象数组)但是当我使用 console.log() 或 console.dir() 它时,它总是显示它作为“对象”。我尝试了 JSON.parse()、JSON.stringify() 和这两种方法,但都没有奏效。

我的目标是从this.reportNavJSONMain 访问reportSections,但是当我访问this.reportNavJSONMain.reportSections 时,reportSections 不是 this.reportNavJSONMain 的一部分。但是当我console.dir(this.reportNavJSONMain)console.log(this.reportNavJSONMain) 时,它会显示:

{"reportSections":[
     {"name":"...","display":true,"nav":true,"reportGroups":
          {"reports":
              [{"name":"Client Relationship Report","url": .....}

【问题讨论】:

  • 能否改进一下格式
  • @Zze,是的,我可以,什么是正确的格式让它看起来更可读?

标签: javascript json angular typescript


【解决方案1】:

你不能导航/迭代一个字符串,但你可以一个对象!

(我假设 this.reportNavJSONMain 被声明为 varObject

如果数据的类型为Object

).then((data)=>{
    this.reportNavJSONMain = data;
})

如果数据的类型是String

).then((data)=>{
    this.reportNavJSONMain = JSON.parse(data);
})


如何在 Javascript 中实现此功能的示例,

var object = {
  "reportSections": [
    {
      "name": "...",
      "display": true,
      "nav": false,
      "reportGroups": {
        "reports": [
          {
            "name": "...",
            "url": "reportLibrary.tableau",
            "nav": true,
            "params": {
              "reportName": "clientRelationshipReport",
              "reportTitle": "Client Relationship Report",
              "reportUrl": "...",
              "reportHeight": "4030px"
            },
            "filters": "clientName,brokerName,entity,budgetClass,practice,office"
          }
        ]
      }
    }
  ]
}

var p = new Promise((resolve, reject) => {
  resolve(object);
});

p.then((data) => {
  data.reportSections.forEach((section) => {
    console.log(section.reportGroups);
  })
});

【讨论】:

  • 我不认为 this.reportNavJSONMain 是一个字符串?控制台会在对象周围显示引号
  • @ezzzCash 这是您发布的代码:this.reportNavJSONMain = JSON.stringify(data);,它将对象转换为字符串。你想要JSON.parse() 吗?
  • 当我执行 JSON.parse() 时,它会在控制台上显示“对象”,并在下面显示 JSON 的属性。但是,我仍然无法访问 reportSections
  • 好的,所以我将其初始化为 .then((data: Object)=&gt;{ this.reportNavJSONMain = data; console.dir(this.reportNavJSONMain.reportSections); console.dir(this.reportNavJSONMain); })this.reportNavJSONMain.reportSections 现在在控制台上是“未定义”(这是我最初的问题)
  • @ezzzCash 我添加了一个模仿正确功能的javascript sn-p - 希望这能澄清我的答案。
【解决方案2】:

您正在使用 JSON.stringify() 将 JSON 结果转换为字符串,在您的 http 结果上您想在服务中调用 result.json()。这样,您立即将结果作为 json。

【讨论】:

  • 对不起,我忘了给你看我的服务中的代码,我已经在这样做了。我将编辑我的问题以在服务中添加我的代码
  • 在您的服务中,您还返回一个字符串,只需从服务返回 response.json() 并将其放入组件的 reportNavJSONMain 属性中。
猜你喜欢
  • 2016-07-02
  • 1970-01-01
  • 1970-01-01
  • 2016-06-12
  • 2020-12-25
  • 1970-01-01
  • 2016-07-28
  • 1970-01-01
  • 2016-10-29
相关资源
最近更新 更多