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

标签 python json loops

我有一堆来自 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 else print '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

关于python - 检查键是否存在并使用 Python 迭代 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24898797/

相关文章:

loops - 标签 - break vs continue vs goto

javascript - 循环遍历数组中的 json 响应

python - 符号表的限制?

python - 如何检查文件内的所有文件夹和文件内的子文件夹是否存在特定字符串

Javascript 对象 push() 函数

java - 将 JSON 转换为 CSV

ruby - 在字符串数组中查找字符串的最快方法

Python 数据框分组

python - python中路径的第一个元素

java - 如何获取动态 JSON 数组中每个对象的键?