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

2024-04-19 07:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一堆来自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":...}]}

我想让代码把打印成

我不知道怎么做。

谢谢!


Tags: to数据namefromidjsondataget
3条回答

为类似的事情创建helper实用程序方法是一个很好的实践,这样当您需要更改属性验证的逻辑时,它将位于一个位置,并且代码对跟随者的可读性更强。

例如,在json_utils.py中创建助手方法(或使用静态方法的类JsonUtils):

def get_attribute(data, attribute, default_value):
    return data.get(attribute) or default_value

然后在项目中使用它:

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'))

重要提示:

我使用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'

在我的应用程序中,获取值为“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

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

h.get('b', 'Default value')

相关问题 更多 >