分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

json深层理解

发布时间:2023-09-06 01:54责任编辑:顾先生关键词:jsjson

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

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved