python - 使用python从JSON对象中提取数据
问题描述
我正在尝试从看起来像这样的 JSON 对象将数据放入 SAMPLES 和 LABELS 变量中。
{
"samples": [
[
28,
25,
95
],
[
21,
13,
70
],
[
13,
21,
70
]
],
"labels": [
1,
2,
3
]
}
我正在使用的代码
with open(data, 'r') as d:
complete_data = json.load(d)
for a in complete_data:
samples = a['samples']
lables = a['lables']
但它说
样本 = a['样本']
TypeError:字符串索引必须是整数
解决方案
要从中获取数据'samples'
,'labels'
您不需要使用循环。尝试这个:
import json
with open('data.json', 'r') as d:
complete_data = json.load(d)
samples = complete_data['samples']
labels = complete_data['labels']
print(samples)
print(labels)
输出:
[[28, 25, 95], [21, 13, 70], [13, 21, 70]]
[1, 2, 3]
推荐阅读
- graphql - 如何在反应 apollo-client graphql 中手动设置自定义标头?
- r - 创建一个向量,其顺序元素重复多次作为相邻列中的相应值
- html - Tailwindcss - 将两个不同大小的文本与底线对齐
- webpack - 如何将 JST 预处理器从 sprockets 转换为 webpacker?
- sql - 为什么我在使用日期操作时不能在别名中使用列名
- node.js - 节点调度模块无法长时间调度 Cron 作业
- applescript - AppleScript 将单个数据文件刻录到 CD
- download - Remove fancybox Download & Share Icons
- javascript - 如何在 Nodejs 中以 JSON 格式保存标准输入数据
- android - Ad Banner is changing color of layout