python - 将 JSON 字符串转换为字典未列出

我正在尝试传入一个 JSON 文件并将数据转换为字典。

到目前为止,这就是我所做的:

import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)

我希望 json1_datadict 类型,但当我使用 检查它时,它实际上是 list 类型>类型(json1_data)

我错过了什么?我需要这是一本字典,这样我才能访问其中一个键。

最佳答案

您的 JSON 是一个内部包含单个对象的数组,因此当您读取它时,您会得到一个包含字典的列表。您可以通过访问列表中的第 0 项来访问您的字典,如下所示:

json1_data = json.loads(json1_str)[0]

现在您可以按预期访问存储在 datapoints 中的数据:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] 不符合您的预期。 datapoints[0:5] 返回一个仅包含前 5 个元素的新列表切片,然后在其末尾添加 [0] 将只取第一个元素 来自结果列表切片。您需要使用 list comprehension 来获得所需的结果:

[p[0] for p in datapoints[0:5]]

这是计算平均值的简单方法:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

如果您愿意安装 NumPy ,那就更简单了:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

, 运算符与 NumPy 数组的切片语法结合使用,可以实现您最初期望的列表切片行为。

https://stackoverflow.com/questions/19483351/

相关文章:

java - 如何指定 jackson 只使用字段 - 最好是全局

json - 如何通过 JSON 文件传递​​有效载荷以进行 curl?

python - NumPy 数组不是 JSON 可序列化的

javascript - 将带有数字键的 JavaScript 对象转换为数组

java - 将 JSON 转换为 map

c# - 将 JSON 字符串转换为 C# 对象

json - 如何使用 JSON 对象初始化 TypeScript 对象?

java - 在 Java 中使用 JSON 的 HTTP POST

json - JSON 语法是否允许对象中有重复的键?

json - HTTP 中的 "406-Not Acceptable Response"是什么?