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

2024-04-20 12:31:59 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我期望json1_datadict类型,但当我用type(json1_data)检查时,它实际上是list类型。

我错过了什么?我需要这是一本字典,这样我才能找到其中一把钥匙。


Tags: 文件数据importjson类型readdata字典
3条回答

这里有一个简单的片段,它读取字典中的json文本文件。注意,json文件必须遵循json标准,因此它必须有"双引号,而不是'单引号。

您的JSON dump.txt文件:

{"test":"1", "test2":123}

Python脚本:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

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

json1_data = json.loads(json1_str)[0]

现在您可以访问存储在数据点中的数据,正如您所期望的那样:

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数组的切片语法一起使用,具有您最初期望的列表切片行为。

您可以使用以下选项:

import json

 with open('<yourFile>.json', 'r') as JSON:
       json_dict = json.load(JSON)

 # Now you can use it like dictionary
 # For example:

 print(json_dict["username"])

相关问题 更多 >