python - 无法访问用 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 数据。
解决方案
您不需要加载该行,您可以加载文件(假设其有效的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)
推荐阅读
- firebase - Vue页面如何获取开头的数据
- python - 我似乎无法找到一种方法来获取 Pyqtgraph 中 ScatterPlotItem 的所有点的列表
- bots - 用户进入组时如何触发方法?
- python - 在 Linux 中以编程方式检查特定类型的设备
- google-apps-script - Google 表格脚本编辑器仅查看
- opengl - 更好地了解阴影痤疮
- python-3.x - 使用 Anaconda 管理 python 安装设置 Hydrogen 和 Atom
- r - 德雷克:如何使用组合向目标发送参数?
- reactjs - Gutenberg 和 ESNext 中的多个高阶组件
- flutter - 扑影难看