我从Facebook帖子中获得了一堆JSON数据,如下所示:
{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}
JSON数据是半结构化的,并且所有数据都不相同。下面是我的代码:
import json
str = '{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}'
data = json.loads(str)
post_id = data['id']
post_type = data['type']
print(post_id)
print(post_type)
created_time = data['created_time']
updated_time = data['updated_time']
print(created_time)
print(updated_time)
if data.get('application'):
app_id = data['application'].get('id', 0)
print(app_id)
else:
print('null')
#if data.get('to'):
#... This is the part I am not sure how to do
# Since it is in the form "to": {"data":[{"id":...}]}
我希望代码将to_id打印为1543,否则打印'null'
我不确定该怎么做。
in
检查,以及raise
是否缺少这些检查?只需访问它而不进行检查,您将获得完全相同的行为(除了用KeyError
而不是代替ValueError
)。