检查键是否存在,并使用Python迭代JSON数组

我有一堆来自Facebookpost的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'

我不知道如何做到这一点。

谢谢!

 import json jsonData = """{"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"}""" def getTargetIds(jsonData): data = json.loads(jsonData) if 'to' not in data: raise ValueError("No target in given data") if 'data' not in data['to']: raise ValueError("No data for target") for dest in data['to']['data']: if 'id' not in dest: continue targetId = dest['id'] print("to_id:", targetId) 

输出:

 In [9]: getTargetIds(s) to_id: 1543 

如果你想要的只是检查是否存在密钥

 h = {'a': 1} 'b' in h # returns False 

如果你想检查是否有一个关键的价值

 h.get('b') # returns None 

如果缺less实际值,则返回默认值

 h.get('b', 'Default value') 
 jsonData = """{"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"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}""" def getTargetIds(jsonData): data = json.loads(jsonData) for dest in data['to']['data']: print("to_id:", dest.get('id', 'null')) 

尝试一下:

 >>> getTargetIds(jsonData) to_id: 1543 to_id: null 

或者,如果您只是想跳过缺lessid的值而不打印'null'

 def getTargetIds(jsonData): data = json.loads(jsonData) for dest in data['to']['data']: if 'id' in to_id: print("to_id:", dest['id']) 

所以:

 >>> getTargetIds(jsonData) to_id: 1543 

当然,在现实生活中,你可能不想print每个ID,而是存储它们,并与他们做某些事情,但这是另一个问题。

为这样的事情创build助手实用程序方法是一个很好的习惯,所以无论何时需要更改属性validation的逻辑,它都在一个地方,代码对于追随者而言将更具可读性。

例如,在json_utils.py创build一个辅助方法(或带有静态方法的json_utils.py类):

 def has_attribute(data, attribute): return attribute in data and data[attribute] is not None 

然后在你的项目中使用它:

 from json_utils import has_attribute if has_attribute(data, 'to') and has_attribute(data['to'], 'data'): for item in data['to']['data']: if has_attribute(item, 'id'): to_id = item['id'] else: to_id = 'null' print('The id is: %s' % to_id)