Python 将JSON字符串转换为字典非列表
我试图传入一个JSON文件,并将数据转换成一个字典 到目前为止,我所做的就是:Python 将JSON字符串转换为字典非列表,python,json,list,python-3.x,dictionary,Python,Json,List,Python 3.x,Dictionary,我试图传入一个JSON文件,并将数据转换成一个字典 到目前为止,我所做的就是: import json json1_file = open('json1') json1_str = json1_file.read() json1_data = json.loads(json1_str) 我希望json1\u数据是一个dict类型,但当我用type(json1\u数据)检查它时,它实际上是一个列表类型 我错过了什么?我需要这是一本字典,这样我就可以访问其中一个键 你的JSON是一个数组,里面只有
import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)
我希望json1\u数据
是一个dict
类型,但当我用type(json1\u数据)
检查它时,它实际上是一个列表
类型
我错过了什么?我需要这是一本字典,这样我就可以访问其中一个键 你的JSON是一个数组,里面只有一个对象,所以当你在里面读它的时候,你会得到一个里面有字典的列表。您可以通过访问列表中的项目0来访问词典,如下所示:
json1_data = json.loads(json1_str)[0]
现在,您可以访问存储在数据点中的数据,正如您所期望的那样:
datapoints = json1_data['datapoints']
如果有人能咬我,我还有一个问题:我试图取这些数据点(即数据点[0][0])中第一个元素的平均值。为了列出它们,我尝试使用数据点[0:5][0],但我得到的只是包含两个元素的第一个数据点,而不是只包含第一个元素的前5个数据点。有办法做到这一点吗
datapoints[0:5][0]
没有达到您的期望datapoints[0:5]
返回一个只包含前5个元素的新列表片,然后在其末尾添加[0]
,将只获取结果列表片中的第一个元素。要获得想要的结果,您需要使用的是:
以下是计算平均值的简单方法:
sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8
如果您愿意安装,则更容易:
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数组的切片语法具有您最初期望的列表切片行为。下面是一个简单的片段,从字典中读取json
文本文件中的内容。请注意,您的json文件必须遵循json标准,因此它必须有“
双引号,而不是”
单引号
您的JSON dump.txt文件:
{"test":"1", "test2":123}
import json
with open('/your/path/to/a/dict/dump.txt') as handle:
dictdump = json.loads(handle.read())
Python脚本:
{"test":"1", "test2":123}
import json
with open('/your/path/to/a/dict/dump.txt') as handle:
dictdump = json.loads(handle.read())
将JSON数据加载到字典中的最佳方法是使用内置JSON加载程序 下面是可以使用的示例片段。
import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])
导入json
f=打开(“data.json”)
data=json.load(f))
f、 关闭()
类型(数据)
打印(数据[])
您可以使用以下功能:
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"])
导入json
将open('.json',r')作为json:
json_dict=json.load(json)
#现在你可以像使用字典一样使用它了
#例如:
打印(json_dict[“用户名”])
使用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.")**
我正在使用RESTAPI的Python代码,所以这是为那些从事类似项目的人准备的 我使用POST请求从URL提取数据,原始输出是JSON。出于某种原因,输出已经是一个字典,而不是一个列表,我可以立即引用嵌套的字典键,如下所示:
datapoint_1 = json1_data['datapoints']['datapoint_1']
datapoints_1在datapoints字典中的位置。你能给我们看一个JSON文件的例子吗?我正在尝试访问'datapoints'键,你的基本项是一个列表。试试
json1_data[0]['datapoints']
。我猜你的JSON是一个列表,而不是我们的讲师在键入(json1_数据)时给我们看的字典他的是“dict”类型。谢谢大家的帮助!谢谢大家!如果有人能回答我,我还有一个问题:我正在尝试计算这些数据点(即数据点[0][0])中第一个元素的平均值。为了列出它们,我尝试了数据点[0:5][0]但是我得到的只是两个元素的第一个数据点,而不是想要得到只包含第一个元素的前5个数据点。有没有办法做到这一点?@lawchit-看看我的更新答案。如果你要用这些数据做数学运算,我强烈推荐使用NumPy。这一个值得再加100分:-)我一直在寻找此解决方案持续1整天在这种情况下,“打开”命令会自动关闭json文件吗?我注意到您没有使用上下文管理器。@Moondra U必须使用close()来关闭files@Moondra您也可以使用with()
操作符,而不必从站点with open(“欢迎使用“.txt”)作为文件:
请参阅:这是问题的答案吗?