无法访问此JSON嵌套对象

时间:2019-02-28 08:07:54

标签: json firebase angular7

我一直在尝试访问此嵌套的json对象,它是firebase的响应。我在前端使用的是Angle 7,我想在页面上显示此数据。

返回的数据:

{"-LZn4rzsI3_0Mm0pcUZ2":{"email":"primedine@gmail.com","name":"Prime 
Dine Restaurant","phone":9512556799},"-LZn4vGB7v0frlDywQ1x": 
{"email":"mango@gmail.com","name":"@Mango","phone":7992556799},"- 
LZn4xyGeo-yh6945mKC":{"email":"desitadka@gmail.com","name":"Global 
Desi Tadka","phone":8872556799},"-LZn50DSU3JNw6hNcdzz": 
{"email":"vishala@gmail.com","name":"VIshala","phone":9972556799}}

到目前为止,我已经尝试通过将响应放入变量然后使用data [0] [name]进行访问,但是它不起作用。我也尝试仅通过键(在此命名)来访问它,但是那也不起作用。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您应使用JSON.parse(),如下所示:

var json = '{"-LZn4rzsI3_0Mm0pcUZ2":{"email":"primedine@gmail.com","name":"Prime 
Dine Restaurant","phone":9512556799},"-LZn4vGB7v0frlDywQ1x": 
{"email":"mango@gmail.com","name":"@Mango","phone":7992556799},"- 
LZn4xyGeo-yh6945mKC":{"email":"desitadka@gmail.com","name":"Global 
Desi Tadka","phone":8872556799},"-LZn50DSU3JNw6hNcdzz": 
{"email":"vishala@gmail.com","name":"VIshala","phone":9972556799}}';
var obj = JSON.parse(json);

//Use the object as desired, for example:
Object.keys(obj).forEach(e =>
  console.log(`key = ${e}  name = ${obj[e].name}`)
);