【问题标题】:extracting data from JSON object with python使用python从JSON对象中提取数据
【发布时间】:2020-06-02 14:59:48
【问题描述】:

我正在尝试从如下所示的 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']

但它说

samples = a['samples']

TypeError:字符串索引必须是整数

【问题讨论】:

  • 移除 for 循环 - 使用 samples = complete_data['samples']
  • 您试图使用字典的字符串表示。你应该先把它转换成字典。使用 ast.literal_eval 转换字典
  • @ikibir,我搜索了 ast.literal_eval,它说它用于评估输入,检查它是否有效。你能指导我更多吗?
  • @Abdullah 该错误发生在哪一行?
  • @EdWard,您的解决方案有效,我将变量从 with 块中取出,它有效。非常感谢

标签: python json extraction


【解决方案1】:

要从'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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2021-11-24
    • 2017-04-16
    • 2020-05-06
    • 1970-01-01
    • 2011-09-18
    相关资源
    最近更新 更多