【问题标题】:How can we structure array of dictionary in firebase realtime database?我们如何在firebase实时数据库中构造字典数组?
【发布时间】:2019-09-14 22:28:58
【问题描述】:

我想在 firebase 实时数据库中创建下面的 json 结构

{
    "doner": [
        {
            "firstName": "Sandesh",
            "lastName": "Sardar",
            "location": [50.11, 8.68],
            "mobile": "100",
            "age": 21
        },
        {
            "firstName": "Akash",
            "lastName": "saw",
            "location": [50.85, 4.35],                
            "mobile": "1200",                
            "age": 22                
        },            
        {                
            "firstName": "Sahil",                
            "lastName": "abc",                
            "location": [48.85, 2.35],                
            "mobile": "325846",                
            "age": 23                
        },            
        {                
            "firstName": "ram",                
            "lastName": "abc",                
            "location": [46.2039, 6.1400],                
            "mobile": "3257673",                
            "age": 34                
        }]        
}

但是当我在firebase实时数据库中导入文件时,它变成了下面的结构]1

我相信这不是字典数组,而是多个字典的字典。

有没有办法在 firebase 中构造字典数组?

【问题讨论】:

  • 生成的结构有什么问题?每个条目都有一个key,你可以把firebase实时数据库想象成一个json
  • @barotia 据我了解,我无法直接使用数组索引迭代 doner,但由于 firebase 结构,我将不得不使用 key 进行迭代。
  • 嗯,这有什么问题?
  • @barotia 因为如果我必须在数据库中添加或删除某些内容,我将不得不为此找到关键。我想如果我有数组我可以简单地删除,使用索引追加
  • 使用 firebase,无论如何您都不会使用索引删除,要删除,您必须为特定子项添加路径,因为需要 Id。

标签: json firebase firebase-realtime-database


【解决方案1】:

Firebase 实时数据库本身并不以您想要的格式存储数组。相反,它将数组存储为键值对,键是数组中每个项目的索引(字符串表示形式)。

当您从 Firebase 读取数据时(通过 SDK 或通过 REST API),它会将此地图转换回数组。

所以你看到的是预期的行为,没有办法改变它。

如果您想详细了解 Firebase 如何处理数组及其原因,我建议您在此处查看 Kato 的博文:Best Practices: Arrays in Firebase

【讨论】:

    猜你喜欢
    • 2020-01-20
    • 2018-06-05
    • 2014-11-06
    • 1970-01-01
    • 2019-02-02
    • 2017-03-04
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多