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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19483351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:52:46  来源:igfitidea点击:

Converting JSON String to Dictionary Not List

pythonjsonlistpython-3.xdictionary

提问by lawchit

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

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

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_datato be a dicttype but it actually comes out as a listtype when I check it with type(json1_data).

我期待json1_data成为一个dict类型,但它实际上出来的list,当我和检查类型type(json1_data)

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

我错过了什么?我需要这是一本字典,以便我可以访问其中一个键。

采纳答案by DaoWen

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:

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

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapointsjust 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?

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

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:

datapoints[0:5][0]不会做你所期望的。datapoints[0:5]返回一个只包含前 5 个元素的新列表切片,然后[0]在它的末尾添加将只从结果列表 slice 中获取第一个元素。你需要用来得到你想要的结果是一个列表理解

[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:

如果您愿意安装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

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

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

回答by user1767754

Here is a simple snippet that read's in a jsontext file from a dictionary. Note that your json file must follow the json standard, so it has to have "double quotes rather then 'single quotes.

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

Your JSON dump.txt File:

您的 JSON dump.txt 文件:

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

Python Script:

Python脚本:

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

回答by Sampat Kumar

The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.

将 JSON 数据加载到字典中的最佳方法是您可以使用内置的 json 加载器。

Below is the sample snippet that can be used.

下面是可以使用的示例代码段。

import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])

回答by userguest

You can use the following:

您可以使用以下内容:

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"])

回答by Mohit Mishra

pass the data using javascript ajax from get methods

使用 javascript ajax 从 get 方法传递数据

    **//javascript function    
    function addnewcustomer(){ 
    //This function run when button click
    //get the value from input box using getElementById
            var new_cust_name = document.getElementById("new_customer").value;
            var new_cust_cont = document.getElementById("new_contact_number").value;
            var new_cust_email = document.getElementById("new_email").value;
            var new_cust_gender = document.getElementById("new_gender").value;
            var new_cust_cityname = document.getElementById("new_cityname").value;
            var new_cust_pincode = document.getElementById("new_pincode").value;
            var new_cust_state = document.getElementById("new_state").value;
            var new_cust_contry = document.getElementById("new_contry").value;
    //create json or if we know python that is call dictionary.        
    var data = {"cust_name":new_cust_name, "cust_cont":new_cust_cont, "cust_email":new_cust_email, "cust_gender":new_cust_gender, "cust_cityname":new_cust_cityname, "cust_pincode":new_cust_pincode, "cust_state":new_cust_state, "cust_contry":new_cust_contry};
    //apply stringfy method on json
            data = JSON.stringify(data);
    //insert data into database using javascript ajax
            var send_data = new XMLHttpRequest();
            send_data.open("GET", "http://localhost:8000/invoice_system/addnewcustomer/?customerinfo="+data,true);
            send_data.send();

            send_data.onreadystatechange = function(){
              if(send_data.readyState==4 && send_data.status==200){
                alert(send_data.responseText);
              }
            }
          }

django views

Django 视图

    def addNewCustomer(request):
    #if method is get then condition is true and controller check the further line
        if request.method == "GET":
    #this line catch the json from the javascript ajax.
            cust_info = request.GET.get("customerinfo")
    #fill the value in variable which is coming from ajax.
    #it is a json so first we will get the value from using json.loads method.
    #cust_name is a key which is pass by javascript json. 
    #as we know json is a key value pair. the cust_name is a key which pass by javascript json
            cust_name = json.loads(cust_info)['cust_name']
            cust_cont = json.loads(cust_info)['cust_cont']
            cust_email = json.loads(cust_info)['cust_email']
            cust_gender = json.loads(cust_info)['cust_gender']
            cust_cityname = json.loads(cust_info)['cust_cityname']
            cust_pincode = json.loads(cust_info)['cust_pincode']
            cust_state = json.loads(cust_info)['cust_state']
            cust_contry = json.loads(cust_info)['cust_contry']
    #it print the value of cust_name variable on server
            print(cust_name)
            print(cust_cont)
            print(cust_email)
            print(cust_gender)
            print(cust_cityname)
            print(cust_pincode)
            print(cust_state)
            print(cust_contry)
            return HttpResponse("Yes I am reach here.")**

回答by jeppoo1

I am working with a Python code for a REST API, so this is for those who are working on similar projects.

我正在使用用于 REST API 的 Python 代码,因此这适用于从事类似项目的人。

I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:

我使用 POST 请求从 URL 中提取数据,原始输出是 JSON。出于某种原因,输出已经是一个字典,而不是一个列表,我可以立即引用嵌套的字典键,如下所示:

datapoint_1 = json1_data['datapoints']['datapoint_1']

where datapoint_1 is inside the datapoints dictionary.

其中 datapoint_1 位于数据点字典内。