Check if key exists and iterate the JSON array using Python
我有一堆来自facebook帖子的json数据,如下所示:
1 | {"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数据是半结构化的,所有数据都不相同。以下是我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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":...}]} |
我想把代码打印成1543,否则打印"空"
我不知道该怎么做。
谢谢!
1 2 3 4 5 6 7 8 9 10 | import json jsonData ="""{"from": {"id":"8","name":"Mary Pinter <div class="suo-content">[collapse title=""]<ul><li>为什么这种明确的<wyn>in</wyn>检查和<wyn>raise</wyn>检查会丢失?只需在不进行检查的情况下访问它,就可以获得完全相同的行为(除了使用<wyn>KeyError</wyn>而不是<wyn>ValueError</wyn>)。</li></ul>[/collapse]</div><hr> <p> If all you want is to check if key exists or not </p> [cc lang="python"]h = {'a': 1} 'b' in h # returns False |
如果要检查是否有键的值
1 | h.get('b') # returns None |
如果缺少实际值,则返回默认值
1 | h.get('b', 'Default value') |
为类似的事情创建助手实用程序方法是一个很好的实践,这样当您需要更改属性验证的逻辑时,它将在一个位置,并且代码将更易于跟随者阅读。
例如,在
1 2 | def get_attribute(data, attribute, default_value): return data.get(attribute) or default_value |
然后在项目中使用它:
1 2 3 4 5 6 7 8 9 10 11 | from json_utils import get_attribute def my_cool_iteration_func(data): data_to = get_attribute(data, 'to', None) if not data_to: return data_to_data = get_attribute(data_to, 'data', []) for item in data_to_data: print('The id is: %s' % get_attribute(item, 'id', 'null')) |
重要注意事项:
我使用
1 2 | {'my_key': None}.get('my_key', 'nothing') # returns None {'my_key': None}.get('my_key') or 'nothing' # returns 'nothing' |
在我的应用程序中,获取值为"null"的属性与完全不获取该属性相同。如果你的用法不同,你需要改变它。
1 2 3 | jsonData ="""{"from": {"id":"8","name":"Mary Pinter <hr>[cc lang="python"]if"my_data" in my_json_data: print json.dumps(my_json_data["my_data"]) |