javascript - 无法正确读取 json 文件
问题描述
我是新来的,我没有找到任何问题的答案,或者也许我没有以正确的方式查找。我昨天开始实习,这是我第一次使用 Angular。目前,我正在阅读一个 json 文件并获取一些信息,但是我使用语法进行了测试并且它有效,但是服务器发送的文件有点不同。我一直在测试这个 json 文件(不是来自公司的文件)
[
{"name": "Justine", "age": 25, "sexe": "femme"},
{"name": "Alex", "age": 23, "sexe": "homme"}
]
但是如果我把[变成{,它就不再起作用了
{
{"name": "Justine", "age": 25, "sexe": "femme"},
{"name": "Alex", "age": 23, "sexe": "homme"}
}
先感谢您 !
编辑:这是组件的代码
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));
}
}
服务代码
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);
}
}
我忘了说我的文件来自 API 并且没有 [,只有 {
解决方案
您需要将数据放在 json 的根属性中
{
"root": [
{"name": "Justine", "age": 25, "sexe": "femme"},
{"name": "Alex", "age": 23, "sexe": "homme"}
]
}
推荐阅读
- reactjs - 打开时反应模式滚动顶部
- python - Python语音识别音频的最小激活能级
- html - 渐变不覆盖全文
- jquery - 如何附加输入值
- html - 下拉确实有效,但不是我想要的方式?
- java - JasperReports Studio-Sorting HashMap 和错误“无法解析收集器”
- python - ReactJS + Flask 在本地工作,但不在 Heroku
- ubuntu - Visual Studio Code 和 WSL Ubuntu (Windows)
- docker - 为什么 Kubernetes 服务无法在 Minikube 上正常运行?(拒绝连接)
- php - 在 laravel 迁移中保存加密价格值