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

2025-02-12 10:03:00
admin
原创
48
摘要:问题描述:我正在尝试传递一个 JSON 文件并将数据转换为字典。到目前为止,这是我所做的:import json json1_file = open('json1') json1_str = json1_file.read() json1_data = json.loads(json1_str) 我希望jso...

问题描述:

我正在尝试传递一个 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)`

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


解决方案 1:

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

json1_data = json.loads(json1_str)[0]

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

datapoints = json1_data['datapoints']

如果有人能回答我的问题,我还有一个问题:我试图取这些数据点中第一个元素的平均值(即 datapoints0)。为了列出它们,我尝试执行 datapoints0:5,但我得到的只是包含两个元素的第一个数据点,而不是想要获取仅包含第一个元素的前 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 数组切片语法的运算符具有您最初对列表切片所期望的行为。

解决方案 2:

这是一个从字典中读取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 加载器。

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

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

解决方案 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.")**
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1590  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1361  
  信创产品在政府采购中的占比分析随着信息技术的飞速发展以及国家对信息安全重视程度的不断提高,信创产业应运而生并迅速崛起。信创,即信息技术应用创新,旨在实现信息技术领域的自主可控,减少对国外技术的依赖,保障国家信息安全。政府采购作为推动信创产业发展的重要力量,其对信创产品的采购占比情况备受关注。这不仅关系到信创产业的发展前...
信创和国产化的区别   18  
  信创,即信息技术应用创新产业,旨在实现信息技术领域的自主可控,摆脱对国外技术的依赖。近年来,国货国用信创发展势头迅猛,在诸多领域取得了显著成果。这一发展趋势对科技创新产生了深远的推动作用,不仅提升了我国在信息技术领域的自主创新能力,还为经济社会的数字化转型提供了坚实支撑。信创推动核心技术突破信创产业的发展促使企业和科研...
信创工作   18  
  信创技术,即信息技术应用创新产业,旨在实现信息技术领域的自主可控与安全可靠。近年来,信创技术发展迅猛,对中小企业产生了深远的影响,带来了诸多不可忽视的价值。在数字化转型的浪潮中,中小企业面临着激烈的市场竞争和复杂多变的环境,信创技术的出现为它们提供了新的发展机遇和支撑。信创技术对中小企业的影响技术架构变革信创技术促使中...
信创国产化   19  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用