251

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

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

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

我期待json1_data成为dict一种list类型,但当我使用type(json1_data).

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

4

6 回答 6

323

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

于 2013-10-20T22:05:58.730 回答
22

这是一个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())
于 2018-01-15T21:58:05.840 回答
12

您可以使用以下内容:

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"])
于 2019-04-21T19:00:37.520 回答
3

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

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

import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])
于 2018-01-17T10:57:00.323 回答
1

我正在使用 REST API 的 Python 代码,所以这适用于那些从事类似项目的人。

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

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

其中 datapoint_1 在 datapoints 字典中。

于 2019-11-20T11:47:05.267 回答
-2

使用 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 视图

    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.")**
于 2019-05-10T12:08:57.687 回答