检查密钥是否存在并使用 Python 迭代 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24898797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if key exists and iterate the JSON array using Python
提问by pravi
I have a bunch of JSON data from Facebook posts like the one below:
我有一堆来自 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"}
The JSON data is semi-structured and all is not the same. Below is my code:
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":...}]}
I want the code to print the to_idas 1543 else print 'null'
我希望代码将to_id打印为 1543 否则打印 'null'
I am not sure how to do this.
我不知道该怎么做。
回答by inspectorG4dget
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)
Output:
输出:
In [9]: getTargetIds(s)
to_id: 1543
回答by abarnert
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'))
Try it:
尝试一下:
>>> getTargetIds(jsonData)
to_id: 1543
to_id: null
Or, if you just want to skip over values missing ids instead of printing 'null'
:
或者,如果您只想跳过缺少 id 的值而不是打印'null'
:
def getTargetIds(jsonData):
data = json.loads(jsonData)
for dest in data['to']['data']:
if 'id' in to_id:
print("to_id:", dest['id'])
So:
所以:
>>> getTargetIds(jsonData)
to_id: 1543
Of course in real life, you probably don't want to print
each id, but to store them and do something with them, but that's another issue.
当然,在现实生活中,您可能不想要print
每个 id,而是要存储它们并用它们做一些事情,但这是另一个问题。
回答by athap
If all you want is to check if key exists or not
如果您只想检查密钥是否存在
h = {'a': 1}
'b' in h # returns False
If you want to check if there is a value for key
如果要检查键是否有值
h.get('b') # returns None
Return a default value if actual value is missing
如果缺少实际值,则返回默认值
h.get('b', 'Default value')
回答by MikeL
It is a good practice to create helper utility methods for things like that so that whenever you need to change the logic of attribute validation it would be in one place, and the code will be more readable for the followers.
为这样的事情创建辅助实用程序方法是一种很好的做法,这样无论何时您需要更改属性验证的逻辑,它都会在一个地方,并且代码对于追随者来说更具可读性。
For example create a helper method (or class JsonUtils
with static methods) in json_utils.py
:
例如,在以下位置创建一个辅助方法(或JsonUtils
具有静态方法的类)json_utils.py
:
def get_attribute(data, attribute, default_value):
return data.get(attribute) or default_value
and then use it in your project:
然后在您的项目中使用它:
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'))
IMPORTANT NOTE:
重要的提示:
There is a reason I am using data.get(attribute) or default_value
instead of simply data.get(attribute, default_value)
:
我使用data.get(attribute) or default_value
而不是简单的原因是有原因的data.get(attribute, default_value)
:
{'my_key': None}.get('my_key', 'nothing') # returns None
{'my_key': None}.get('my_key') or 'nothing' # returns 'nothing'
In my applications getting attribute with value 'null' is the same as not getting the attribute at all. If your usage is different, you need to change this.
在我的应用程序中,获取值为 'null' 的属性与根本没有获取属性相同。如果您的用法不同,则需要更改此设置。
回答by Ajit Surendran
if "my_data" in my_json_data:
print json.dumps(my_json_data["my_data"])
回答by tabdiukov
I wrote a tiny function for this purpose. Feel free to repurpose,
我为此编写了一个小函数。随意重新利用,
def is_json_key_present(json, key):
try:
buf = json[key]
except KeyError:
return False
return True