【发布时间】: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