【问题标题】:Converting JSON String to Dictionary Not List将 JSON 字符串转换为字典未列表
【发布时间】:2013-10-29 06:51:38
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你能给我们看一个你的 JSON 文件的例子吗?
  • 我正在尝试访问“数据点”键 graphite.sdsc.edu:8443/render/…
  • 您的基本项目是一个列表。试试json1_data[0]['datapoints']
  • 我猜我会说你的 json 是一个列表而不是字典
  • 根据我们的教练向我们展示的内容,当他输入 type(json1_data) 时,他出现了“dict”类型。谢谢大家的帮助!

标签: python json


【解决方案1】:

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

json1_data = json.loads(json1_str)[0]

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

datapoints = json1_data['datapoints']

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

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 数组的切片语法结合使用,可以实现您最初期望的列表切片行为。

【讨论】:

  • 谢谢你!如果有人能咬,我还有一个问题:我试图取这些数据点中第一个元素的平均值(即数据点 [0] [0])。只是为了列出它们,我尝试做 datapoints[0:5][0] 但我得到的只是包含两个元素的第一个数据点,而不是想要获得仅包含第一个元素的前 5 个数据点。有没有办法做到这一点?
  • @lawchit - 查看我的更新答案。如果您要使用这些数据进行数学运算,我强烈建议您使用 NumPy。
  • 这个值得另外 100 分 :-) 我一整天都在寻找这个解决方案
【解决方案2】:

这是一个简单的 sn-p,它从字典中读取 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())

【讨论】:

    【解决方案3】:

    您可以使用以下内容:

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

    【讨论】:

      【解决方案4】:

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

      下面是可以使用的示例sn-p。

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

      【讨论】:

      • 这种情况下'open'命令会自动关闭json文件吗?我注意到您没有使用上下文管理器。
      • @Moondra U 必须使用 close() 来关闭文件
      • @Moondra 您也可以使用with() 运算符,而不必打开和关闭文件来自该站点:with open("welcome.txt") as file: 请参阅:pythonforbeginners.com/files/with-statement-in-python
      【解决方案5】:

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

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

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

      datapoint_1 在数据点字典中的位置。

      【讨论】:

        【解决方案6】:

        使用 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.")**
        

        【讨论】:

        • 这是问题的答案吗?
        猜你喜欢
        • 2011-07-12
        • 2014-05-23
        • 2019-05-29
        • 1970-01-01
        相关资源
        最近更新 更多