[英]How can I pull nested JSON values from python using dictionaries?
My database is formatted like this: 我的数据库格式如下:
{
"latitude" : 41.884629,
"longitude" : -87.648764,
"name" : "Bar Siena",
"placeID" : "ChIJf3h_t9osDogReehZO7Hgk50",
"vibes" : {
"LGpswrvLgfYppcBG4bpmNzXQVoU2" : {
"rating" : 1,
"timestamp" : 1.477961061358844E9
},
"OSzA2KhTBWS3pxVnCZ6eScAuNDG3" : {
"rating" : 5,
"timestamp" : 1.477955566836665E9
}
}
}
I want to pull both the names of each bar, and every rating corresponding to it in the vibes table. 我想拉出每个条形图的名称,以及振动表中与之对应的每个评级。 My code looks like this: 我的代码看起来像这样:
firebase = pyrebase.initialize_app(config)
db = firebase.database()
for i in range(1,100):
venues = db.child("venues").child(i).get()
dict = (venues.val())
print(dict['name'])
So far i'm only able to get the names, but i'm not sure how to go deeper and get the ratings. 到目前为止,我只能得到这些名字,但我不确定如何更深入地获得收视率。 My database is managed using Firebase, and I'm using a python library called Pyrebase that's just a wrapper for the javascript api. 我的数据库是使用Firebase管理的,我正在使用一个名为Pyrebase的python库,它只是javascript api的包装器。 I'm having trouble because each vibe has a generated hash key so i'm not sure how to go deeper. 我遇到了麻烦,因为每个氛围都有一个生成的哈希键,所以我不确定如何更深入。 Any thoughts? 有什么想法吗?
vibes
probably comes as a dictionary. vibes
可能是一本字典。 What you want are the ratings of each hash key, so you can do something like 你想要的是每个哈希键的评级,所以你可以做类似的事情
for hashkey, vibe_dict in dict['vibes'].items(): # dict is a Python keyword, so it's a bad choice for a variable!
print(hashkey, vibe_dict['rating'])
I am not sure about firebase
, but in plain python you may do it like: 我不确定firebase
,但在普通的python中,你可以这样做:
>>> for vibe in my_json['vibes'].values():
... print vibe['rating']
...
1 # Rating of item 1
5 # Rating of item 2
where my_json
is the dict
build from your json: 其中my_json
是你json的dict
构建:
{
"latitude":41.884629,
"longitude":-87.648764,
"name":"Bar Siena",
"placeID":"ChIJf3h_t9osDogReehZO7Hgk50",
"vibes":{
"LGpswrvLgfYppcBG4bpmNzXQVoU2":{
"rating":1,
"timestamp":1.477961061358844E9
},
"OSzA2KhTBWS3pxVnCZ6eScAuNDG3":{
"rating":5,
"timestamp":1.477955566836665E9
}
}
}
If your venues
variable is a JSON-like object as in example, you can use the standart json
library to work with it: 如果你的venues
变量是一个类似JSON的对象,你可以使用标准的json
库来处理它:
import json
dict_data = json.loads(venues)
print dict_data['latitude']
Btw, it's a bad style of development - to overwrite built-in Python funuctions. 顺便说一下,这是一种糟糕的开发方式 - 覆盖内置的Python功能。 In your example you're overwriting dict(dict is a default Python type-object) 在你的例子中,你覆盖了dict(dict是一个默认的Python类型对象)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.