首页 > 解决方案 > 无法访问用 json.dumps(json.loads(input)) 加载的 JSON

问题描述

假设我有这样的 json 数据。

{"id": {"$oid": "57dbv34346"}, "from": {"$oid": "57dbv34346sbgwe"}, "type": "int"}
{"id": {"$oid": "57dbv34345"}, "from": {"$oid": "57dbv34345sbgwe"}, "type": "int"}

我在python中写了一个这样的脚本

import json
with open('klinks_buildson.json', 'r') as f:
    for line in f:
        distros_dict = json.dumps(json.loads(line), sort_keys=True, indent=4)
        print distros_dict['from']
        print "\n"

但它给了我一个错误:

print distros_dict['from']
TypeError: string indices must be integers, not str

我想要两行中的 from 数据。

标签: pythonjsonparsing

解决方案


您不需要加载该行,您可以加载文件(假设其有效的json);像这样:

with open('klinks_buildjson.json', 'r') as f:
   data = json.load(f)

现在data是一个列表,其中每个项目都是一个对象。您可以遍历它:

for row in data:
   print(row['from'])

要解决您的直接问题,请删除json.dumps用于将对象转换为字符串字符串,这不是您想要的。

distros_dict = json.loads(line)

推荐阅读