python - 如何在 Firebase 中循环 UID

标签 python arrays json firebase firebase-realtime-database

我正在使用 Python 遍历 Firebase DB 返回一组对象,然后随机选择一个对象并返回其值。我一直在使用一个小型测试 JSON DB,我手动构建并导入到 Firebase 中。当我这样做时,数据库的子节点是 0, 1, 2 等...使用下面的代码 - 我可以迭代数据并获取我需要的内容。

我一直在构建一个 CMS,它允许我使用 push() 方法将数据直接输入 Firebase(而不是导入本地 JSON 文档)。

因此,子节点会变成模糊时间戳,如下所示:K036VOR90fh8sd80、KO698fhs7Hf8sfds 等...

现在,当我尝试对节点进行 for 循环时,我在 ln9 caption=.... 处收到以下错误:

类型错误:字符串索引必须是整数

我假设发生这种情况是因为子节点现在是字符串。由于我必须使用 CMS - 我现在如何循环这些节点?

代码:

if 'Item' in intent['slots']:
    chosen_item = intent['slots']['Item']['value']

    result = firebase.get(chosen_item, None)

    if result:
        item_object = []
        for item in result:
            item_object.append(item)

            random_item = (random.choice(item_object))
            caption = random_item['caption']
            audio_src = random_item['audioPath']

以下是 Firebase 的近似外观:

 {
    "1001" : {
"-K036VOR90fh8sd80EQ" : {
  "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_0_1001.mp3",
  "caption" : "Record 0 from 1001"
},
"-KO698fhs7Hf8sfdsWJS" : {
  "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_1_1001.mp3",
  "caption" : "Record 1 from 1001"
  }
 },
 "2001" : {
  "-KOFsPBMKVtwHSOfiDJ" : {
  "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_0_2001.mp3",
  "caption" : "Record 0 from 2001"
},
"-KOFsQvwgF9icSIolU" : {
  "audioPath" : "https://s3.amazonaws.com/bucket-output/audio/audio_1_2001.mp3",
  "caption" : "Record 1 from 2001"
  }
 }
}

最佳答案

需要做的是使用for循环.items()剥离父节点的字典result Python 方法 - 通过键值 (k,v) 和 .append 值 (v)。

这会删除父 Firebase 字典键的结果,即 -KOFsQvwgF9icSIolU

if 'Item' in intent['slots']:
    chosen_item = intent['slots']['Item']['value']

    result = firebase.get(chosen_item, None)

    if result:
        item_object = []
        for k,v in result.items():
            item_object.append(v)

            random_item = (random.choice(item_object))
            caption = random_item['caption']
            audio_src = random_item['audioPath']

关于python - 如何在 Firebase 中循环 UID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38732279/

相关文章:

javascript - 求和特定数组值取决于其他数组的索引值列表

c++ - 在 C/C++ 中实现 JSON RESTful 服务的方法

python - 连接两个具有共同、重复索引的 Pandas 数据框,而不进行笛卡尔积

Python请求 - 打印整个http请求(原始)?

javascript - 如何从脚本中提取数据?

Python 端口监听器(如 NC)

python - numpy 屏蔽不规则数组

C:指向数组的指针和破坏性排序

java - 如何从嵌套的ArrayList中获取JSONObject的属性并将其显示给ListView?

java - JsonDeserialize 在 objectmapper 读取值时也设置继承属性