如何在Firebas中循环UID

2024-04-26 12:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

相应地,子节点变成如下所示的模糊时间戳:K036VOR90fh8sd80, KO698fhs7Hf8sfds等。。。在

现在,当我尝试for循环遍历节点时,在ln9caption=....处得到以下错误:

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的近似值:

^{pr2}$

Tags: 数据代码in数据库jsonforif节点
1条回答
网友
1楼 · 发布于 2024-04-26 12:29:08

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

这将剥离父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']

相关问题 更多 >