• Python接口自动化--Json数据处理 5


    1.Json模块简介,全名JavaScript Object Notation,轻量级的数据交换格式,常用于http请求中。

    Encoding basic Python object hierarchies::

    >>> import json
    >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
    '["foo", {"bar": ["baz", null, 1.0, 2]}]'
    >>> print json.dumps(""fooar")
    ""fooar"
    >>> print json.dumps(u'u1234')
    "u1234"
    >>> print json.dumps('\')
    "\"
    >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
    {"a": 0, "b": 0, "c": 0}
    >>> from StringIO import StringIO
    >>> io = StringIO()
    >>> json.dump(['streaming API'], io)
    >>> io.getvalue()
    '["streaming API"]'

    2.Encode(python->Json),在python和json中的bool值,不同,如下图,所以不转换的话,会报错,所以需要把python的代码经过encode后成为json可识别的数据类型。

    布尔值 python json
    True true
    False false
    # _*_ encoding:utf-8 _*_
    
    import requests
    import json
    
    #python的字典
    payload = {"cye":True,
               "json":False,
               "python":"22137284235",}
    
    print (type(payload))
    #输出
    # <type 'dict'>
    
    #转化成json格式
    data_json = json.dumps(payload)
    print (type(data_json))
    #输出
    # <type 'str'>
    print (data_json)
    # 输出
    # {"python": "22137284235", "json": false, "cye": true}

     Python经过encode成Json的数据类型

    Python Json
    dict object
    list,tuple array
    str,long,float number
    True true
    False false
    None null

    3.decode(Json-->Python)

    字符串:s = {"success":true}

    转成字典:j = s.json(),然后可以通过 j["success"]=true来获取字典的相应key的value值

    Json数据转成python可识别的数据,对应关系如下

    Json Python
    object dict
    array list
    string unicode
    number(int) int,long,
    number(real) float
    true True
    false False
    None null

    实例:查询快递单号

    # _*_ coding:utf-8 _*_
    
    import requests
    import json
    
    id = 8881*************
    url = "http://www.kuaidi.com/index-ajaxselectcourierinfo-%s-yuantong.html"%id
    # print (url)
    
    head = {"Connection": "keep-alive",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6"}
    
    r = requests.get(url=url,headers=head,verify=True)
    j = r.json()
    data = j["data"]
    print (data[0])
    print (data[0]["context"])
    #输出结果
    #{u'context': u'u5ba2u6237 u7b7eu6536u4eba: u90aeu653fu6536u53d1u7ae0 u5df2u7b7eu6536 u611fu8c22u4f7fu7528u5706u901au901fu9012uff0cu671fu5f85u518du6b21u4e3au60a8u670du52a1', u'time': u'2018-01-22 15:43:23'}
    #客户 签收人: 邮政收发章 已签收 感谢使用圆通速递,期待再次为您服务
















  • 相关阅读:
    Asp.net Vnext 模块化实现
    Asp.net Vnext 实现IView
    Asp.net Vnext TagHelpers
    MVC 源码调试
    Asp.net Vnext 中间件实现基本验证
    Azure SQL Federation(联合)
    Microsoft Azure 配置负载均衡
    Asp.net Vnext 调试源码
    阅读文献总结笔记9
    阅读文献总结笔记4
  • 原文地址:https://www.cnblogs.com/cindy-cindy/p/8342780.html
Copyright © 2020-2023  润新知