我试图找出解析对MongoDB的Facebook JSON响应的最佳方法。
FB Event JSON:
{
"description": "Event description",
"name": "Event name",
"place": {
"name": "Place name",
"location": {
"city": "City",
"country": "Country",
"latitude": -26.31604,
"longitude": -48.83667,
"state": "State",
"street": "Street address",
"zip": "000000"
},
"id": "429579150543987"
},
"start_time": "2017-10-27T19:00:00-0200",
"id": "1557095844358825"
}
有时,某个事件并未包含上述所有字段,即:location
和place
是可选的。
所以我做了:
event_dict = {
'id': event['id'],
'name': event['name'],
'start_time': event['start_time']
}
if ("place" in event):
if ("name" in event['place']):
event_dict['place'] = event['place']['name']
if ("location" in event['place']):
if ("street" in event['place']['location']):
event_dict['street'] = event['place']['location']['street']
if ("zip" in event['place']['location']):
event_dict['zip'] = event['place']['location']['zip']
if ("city" in event['place']['location']):
event_dict['city'] = event['place']['location']['city']
if ("state" in event['place']['location']):
event_dict['state'] = event['place']['location']['state']
if ("country" in event['place']['location']):
event_dict['country'] = event['place']['location']['country']
if ("end_time" in event):
event_dict['end_time'] = event['end_time']
if ("description" in event):
event_dict['description'] = event['description']
event_list.append(event_dict)
event_list
是我在MongoDB上保存的词典列表。
我的主要问题是:是否有更好的方法来做,而不是很多if-then-else条件?
答案 0 :(得分:3)
您可以使用key: event.get("key", None)
或嵌套属性val: event.get('key1', None).get('key2', None)
替换大部分if语句
答案 1 :(得分:1)
如果要将json对象转换为dict,则只需执行:
import json
event_dict = json.loads(event)
答案 2 :(得分:1)
要将所有内容转换为单级字典,您可以使用递归函数遍历字典,并在它们出现时提取键值对。像这样:
event = {
"description": "Event description",
"name": "Event name",
"place": {
"name": "Place name",
"location": {
"city": "City",
"country": "Country",
"latitude": -26.31604,
"longitude": -48.83667,
"state": "State",
"street": "Street address",
"zip": "000000"
},
"id": "429579150543987"
},
"start_time": "2017-10-27T19:00:00-0200",
"id": "1557095844358825"
}
one_level_dict = {}
def recursive_extraction(dict, base_string = ""):
for key, value in dict.items():
if type(value) is type({}):
recursive_extraction(value, base_string + key + "_")
else:
one_level_dict[base_string + key] = value
recursive_extraction(event)
print(one_level_dict)
这有点杂乱,但你应该能够根据你的目的修改它。
(这是针对python3的,对于python2,我认为你需要用dict.iteritems()替换dict.items())
编辑:添加了一个base_string来维护较低级别值的json结构的上下文。