简体   繁体   English

无法正确读取 json 文件

[英]Can't read properly a json file

I'm new here, and I did not find any answer to my question, or may-be I did not look up in the right way.我是新来的,我没有找到任何问题的答案,或者也许我没有以正确的方式查找。 I started my intership yesterday, and this is my first time using Angular.我昨天开始实习,这是我第一次使用 Angular。 For now, I am working on reading a json file and getting some informations, however I tested with a syntax and it worked, but the file sent by the server is a bit different.目前,我正在阅读 json 文件并获取一些信息,但是我使用语法进行了测试并且它有效,但是服务器发送的文件有点不同。 I've been testing with this json file (not the one from the company)我一直在测试这个 json 文件(不是来自公司的文件)

[
    {"name": "Justine", "age": 25, "sexe": "femme"},
    {"name": "Alex", "age": 23, "sexe": "homme"}
]

But if I turn [ into {, it does not work anymore但是如果我把[变成{,它就不再起作用了

{
    {"name": "Justine", "age": 25, "sexe": "femme"},
    {"name": "Alex", "age": 23, "sexe": "homme"}
}

Thank you in advance !先感谢您 !

EDIT: This is the code of the component编辑:这是组件的代码

import { InformationsService } from '../informations.service';

@Component({
  selector: 'app-info',
  template: `<h2> Liste </h2>
    <ul *ngFor="let f of info"> 
      <li>{{f.name}} <br></li>
    </ul>`,
  styles: []
})
export class InfoComponent implements OnInit {
  public info = [];

  constructor(private _info : InformationsService) { }

  ngOnInit() {
    this._info.getInfo().subscribe(data => (this.info = data));
  }

}

The code of the service服务代码

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Info } from './informations';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class InformationsService {

  private _url: string = "/assets/data/file.json";
  constructor(private http : HttpClient) { }
  getInfo(): Observable<Info[]>{
    return this.http.get<Info[]>(this._url);
  }
}

I forgot to say that my file is from an API and there is no [, only {我忘了说我的文件来自 API 并且没有 [,只有 {

You need put your data inside a root property of your json您需要将数据放在 json 的根属性中

{
   "root": [
        {"name": "Justine", "age": 25, "sexe": "femme"},
        {"name": "Alex", "age": 23, "sexe": "homme"}
       ]
}

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

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