首页 > 解决方案 > 使用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:字符串索引必须是整数

标签: pythonjsonextraction

解决方案


要从中获取数据'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]

推荐阅读