【发布时间】:2017-10-23 21:03:34
【问题描述】:
我正在尝试找出将 Facebook JSON 响应解析到 MongoDB 的最佳方法。
FB 事件 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 条件?
【问题讨论】:
-
所以你想要一个单级字典作为输出,该字典中有任何键值对?
-
@chasmani 是的,但原始 JSON 中的某些字段是可选的。我的代码正在运行,但我认为这不是更好的方法。
标签: python json mongodb facebook