【问题标题】:How do I loop through UID's in Firebase如何在 Firebase 中循环遍历 UID
【发布时间】:2016-12-08 12:10:31
【问题描述】:

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

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

因此,子节点变成如下所示的混淆时间戳:K036VOR90fh8sd80, KO698fhs7Hf8sfds 等...

现在,当我尝试循环遍历节点时,我在ln9 caption=.... 收到以下错误:

TypeError: string indices must be integers

我假设这是因为子节点现在是字符串。由于我必须使用 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"
  }
 }
}

【问题讨论】:

  • 能否添加指向您用于访问 Firebase 的 Python 库的链接?
  • @FrankvanPuffelen 是的,它是 python-firebase

标签: python arrays json firebase firebase-realtime-database


【解决方案1】:

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

这会剥离父 Firebase 字典键的 result,即 -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']

【讨论】:

    猜你喜欢
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2014-06-02
    • 2010-12-22
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多