【问题标题】:How to print JSON values with keys starting with special characters using angular?如何使用角度以特殊字符开头的键打印 JSON 值?
【发布时间】:2021-01-05 01:37:22
【问题描述】:

当我尝试使用@place 打印时,它会在其他键可以访问时抛出错误。

[{ "ID": "001",
“名称”:“欧亚领鸽”,
“类型”:“鸽子”,
“学名”:“链球菌”,
“@place”:“纽约” }]

这是我得到的错误:
解析器错误:意外的标记词法分析器错误:表达式 [bird.@place] 中第 6 列的意外字符 [@],[{{bird.@place}}] 中第 7 列的预期标识符或关键字

component.ts文件如下:

import { Component } from '@angular/core';    
import { HttpClient } from '@angular/common/http';  
import { HttpErrorResponse } from '@angular/common/http';  

@Component({  
  selector: 'app-root',  
  templateUrl: './app.component.html',  
  styleUrls: ['./app.component.css']  
})  
export class AppComponent {  
  title = 'JSON to Table ';  
  constructor (private httpService: HttpClient) { }  
  arrBirds: string [];  

  ngOnInit () {  
    this.httpService.get('./assets/birds.json').subscribe(  
      data => {  
        this.arrBirds = data as string [];   // FILL THE ARRAY WITH DATA.  
        // this.arrService = JSON.stringify(data);  
        console.log(this.arrBirds);  
      },  
      (err: HttpErrorResponse) => {  
        console.log (err.message);  
      }  
    );  
  }  
}

component.html文件是这样的:

<table *ngIf="arrBirds">
      
      <tr>
          <th>ID</th>
              <th>Name of Bird</th>
                  <th>Type of Bird</th>
                    <th>Place</th>
      </tr>

      
      <tr *ngFor="let bird of arrBirds">
          <td>{{bird.ID}}</td>
              <td>{{bird.Name}}</td>
                  <td>{{bird.Type}}</td>
                    <td>{{bird.@place}}</td>
      </tr>
  </table>

【问题讨论】:

  • 你确定你的大写P(而不是小p)没有错别字吗?
  • 您可以尝试括号表示法bird['@Place'],而不是点表示法。
  • @Guilhermevrs 那是个错误。但是在使用 p 而不是 P 之后仍然出现同样的错误。
  • @MichaelD ui 显示 bird['@place'] 而不是打印值。
  • @SoubhagyaSahoo:请说明您尝试访问该物业的方式和地点。

标签: json angular typescript


【解决方案1】:

正如我在评论中提到的,您可以使用括号表示法而不是点表示法。

<tr *ngFor="let bird of arrBirds">
  <td>{{ bird['ID'] }}</td>
  <td>{{ bird['Name'] }}</td>
  <td>{{ bird['Type'] }}</td>
  <td>{{ bird['@place'] }}</td>
</tr>

工作示例:Stackblitz

【讨论】:

    【解决方案2】:

    在 HTML 中,我不知道调用属性的任何其他方法。我能看到的唯一解决方案是做一个吸气剂。

    在 TS 中

    get place() {
        return bird['@Place']
    }
    

    在 HTML 中

    {{ place }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      相关资源
      最近更新 更多