码迷,mamicode.com
首页 > Web开发 > 详细

json深层理解

时间:2018-05-16 00:21:29      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:false   pre   view   res   div   script   交互   dump   typeof   

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 json
a={"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.py
def 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深层理解

标签:false   pre   view   res   div   script   交互   dump   typeof   

原文地址:https://www.cnblogs.com/gaoyukun/p/9043384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!