【问题标题】:Parse JSON from Firebase to object in Javascript将 JSON 从 Firebase 解析为 Javascript 中的对象
【发布时间】:2021-04-02 16:47:23
【问题描述】:

我从 Firebase 以 Json 格式导出数据库,它看起来很奇怪,但它是合法的 JSON 语法。有谁知道如何将其解析为对象列表?

JSON 代码:

{
  "users" : 
  {
    "GSIgfyiEGtZs5reYe4SpwFJVxDC2" :
    {
      "email" : "anic@hotmail.com",
      "password" : "Dava123",
      "score" : 0,
      "username" : "Anic2",
      "zdate" : "2-3"
    },
    "OHxA5ARnbYdsy9Ga1nxDy0gZQBv1" : {
      "email" : "dava@hotmail.com",
      "password" : "Dava123",
      "score" : 3,
      "username" : "dava",
      "zdate" : "01-03-2021  11:53"
    }
  }
}

【问题讨论】:

  • users 不是 JSON 数组,它是一个 JSON 对象,具有任意数量的运行时属性名称,其值具有固定架构。既然你事先不知道users对象的属性,不妨看看Javascript: Iterating over JSON objects。

标签: javascript json firebase parsing


【解决方案1】:

如果您尝试访问这些值,可以使用键 attribute

var myFireBaseObj = {
  "users" : 
  {
    "GSIgfyiEGtZs5reYe4SpwFJVxDC2" :
    {
      "email" : "anic@hotmail.com",
      "password" : "Dava123",
      "score" : 0,
      "username" : "Anic2",
      "zdate" : "2-3"
    },
    "OHxA5ARnbYdsy9Ga1nxDy0gZQBv1" : {
      "email" : "dava@hotmail.com",
      "password" : "Dava123",
      "score" : 3,
      "username" : "dava",
      "zdate" : "01-03-2021  11:53"
    }
  }
};

console.log( Object.keys(myFireBaseObj));

// if you want to get both values and keys / users etc seperately as objects
var keys = Object.keys(myFireBaseObj );
var values = Object.values(myFireBaseObj );

console.log(keys[0]);
// put your attribute you want here
console.log(values [0]['...']); 

选项 2:如果您想要返回一个数组,请使用 map,例如在下面调整它

 Object.keys(myFireBaseObj).map(function(a,i){
 // whatever you want in the array you map it here
 // you have to customize the nested levels
 return
 [i,myFireBaseObj[a].blahBlah.. ,
 myFireBaseObj[a].password] 
 })

更新:添加示例以显示for loop 以获取key、values

for (var key of Object.keys(myFireBaseObj)) {
    // this will give you the key & values for all properties
    console.log(key + " -> " + p[key])
    // .. process the data here! 
}

【讨论】:

  • 如何获取第二个用户的属性密码?
  • 创建一个for循环。我在上面添加了一个示例。
猜你喜欢
  • 2014-12-02
  • 2014-03-26
  • 2016-05-07
  • 2020-01-08
  • 1970-01-01
  • 2018-05-30
相关资源
最近更新 更多