JSON 是 JavaScript Object Notation 的缩写,它是一种数据交换格式。
在JSON中,允许的值就这6种:
- number:数字类型;
- boolean:true 或 false;
- string:字符串类型;
- null:空值;
- array:数组类型;
- object:对象,使用{ }表示的类型。
python中的json模块
json 模块提供了一种很简单的方式来编码和解码JSON数据。 其中两个主要的函数是 json.dumps()
和 json.loads()
。
python数据转化为JSON数据 —— dumps
import json
data = {
'name':'Tony',
'age':18,
'gender':'male'
}
print(type(data)) # <class 'dict'>
j_data = json.dumps(data)
print(type(j_data)) # <class 'str'>
JSON数据转化为python数据 —— loads
p_data = json.loads(j_data)
print(type(p_data)) # <class 'dict'>
print(p_data["name"]) # Tony
print(p_data["age"]) # 18
上面的两种方法是对python数据结构的转换,如是要将文件类型转换成JSON格式,可以使用 json.dump()
和 json.load()
,仅是去掉了 ‘s’。如:
# Writing JSON data
with open('data.json', 'w') as f:
json.dump(data, f)
# Reading data back
with open('data.json', 'r') as f:
data = json.load(f)
Django发送与接收JSON数据
发送:
# 方式一:
from django.http import HttpResponse
import json
def send_JSON(request):
data = {
'name':'Tony',
'age':18,
'gender':'male'
}
j_data = json.dumps(data)
return HttpResponse(j_data)
# 方式二, 推荐的方式,非常简洁
from django.http import JsonResponse
def send_JSON(request):
data = {
'name':'Tony',
'age':18,
'gender':'male'
}
return JsonResponse(j_data)
接收:
def receive_JSON(request):
data = json.loads(request.body)
name = data["name"] # Tony
age = data["age"] #18
return HttpResponse("接收完成")