且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 JSON 字符串转换为字典而不是列表

更新时间:2023-01-21 22:04:45

你的 JSON 是一个数组,里面只有一个对象,所以当你阅读它时,你会得到一个里面有字典的列表.您可以通过访问列表中的第 0 项来访问您的字典,如下所示:

json1_data = json.loads(json1_str)[0]

现在您可以像预期的那样访问存储在数据点中的数据:

datapoints = json1_data['datapoints']

如果有人可以咬我,我还有一个问题:我试图取这些数据点(即数据点[0][0])中第一个元素的平均值.只是为了列出它们,我尝试做 datapoints[0:5][0] 但我得到的只是包含两个元素的第一个数据点,而不是想要获得仅包含第一个元素的前 5 个数据点.有没有办法做到这一点?

datapoints[0:5][0] 不符合您的预期.datapoints[0:5] 返回一个只包含前 5 个元素的新列表切片,然后在它的末尾添加 [0] 将只包含第一个元素 从结果列表切片.你需要用来获得你想要的结果是一个列表理解::>

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

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

sum(p[0] for p in datapoints[0:5])/5.# 结果是 35.8

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

导入numpyjson1_file = open('json1')json1_str = json1_file.read()json1_data = json.loads(json1_str)[0]数据点 = numpy.array(json1_data['数据点'])avg = 数据点 [0:5,0].mean()# 平均现在是 35.8

, 运算符与 NumPy 数组的切片语法一起使用具有您最初期望的列表切片行为.

I am trying to pass in a JSON file and convert the data into a dictionary.

So far, this is what I have done:

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

I'm expecting json1_data to be a dict type but it actually comes out as a list type when I check it with type(json1_data).

What am I missing? I need this to be a dictionary so I can access one of the keys.

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

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] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

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

Here's a simple way to calculate the mean:

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

If you're willing to install NumPy, then it's even easier:

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

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.