python和json对象的对应:
由下图可知:python对象要想转化为json对象,就必须先转化成json字符串
???????python(对象) ????????--> ?????????????????json(对象) ???????dict ???????????????json字符串 ???????????object ???????list,tuple ?????????json字符串 ???????????array ???????str,unicode ????????json字符串 ?????? string ???????int,long,float ?????json字符串 ???????????number ???????True ???????????????json字符串 ???????????true ???????False ??????????????json字符串 ???????????false ???????None ???????????????json字符串 ???????????null
下面看一个简单的python例子:
import jsona={"name":"gaoyukun","age":"12"} //a是python对象data=json.dumps(a) ??????????????//将a转化为json字符串
print(type(data)) ??????????????print(data)data=json.loads(data) ??????????//将json字符串转化为json对象(因为是在python环境中所以对应dict数据类型,若是在js中则对应object)print(type(data))print(data)#<class ‘str‘>#{"name": "gaoyukun", "age": "12"}#<class ‘dict‘>#{‘name‘: ‘gaoyukun‘, ‘age‘: ‘12‘}
再看一个前后端交互的例子
1.前端发送数据给后端
--------------index.html
<button onclick="fun1()">alss</button><script> ???function fun1(){ ???????var a="fsd"; ???????console.log(typeof a); ?????????//json对象中的string类型 ????????a=JSON.stringify(a); ???????????//将json对象转化为字符串 ???????console.log(typeof a); ???????$.post("/xx/",{name:a},function(data){ ???????????console.log(data); ???????});</script>
--------------views.py
def xx(req):
???if req.method=="POST":
???????print(req.POST.get("name"))
???????return HttpResponse("ggg")
2.后端数据发送给前端
---------------views.pydef xx(req): ???if req.method=="POST": ???????a={"name":"gaoyuku"} ???????data=json.dumps(a) ???????name=req.POST.get("name") ???????return HttpResponse(name)-------------------index.html<script> ???function fun1(){ ???????$.post("/xx/",{name:"gaoyuk"},function(data){ ???????????#data=JSON.parse(data); ????????????//将json字符串转化为json对象,因为后端传来的数据到了js中就是json对象,所以这句话不需要 ???????????console.log(data); ???????????console.log(typeof data); ???????});</script>
json深层理解
原文地址:https://www.cnblogs.com/gaoyukun/p/9043384.html