zoukankan      html  css  js  c++  java
  • Python 下JSON的两种编解码方式实例解析

    概念

      JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。在日常的工作中,应用范围极其广泛。这里就介绍python下它的两种编解码方法:

    使用json函数

      使用 JSON 函数需要导入 json 库:import json。函数含义:

     源码解析:

    # coding= utf-8
    #!/usr/bin/python
    import json
    import sys 
    
    data = {"username":"测试","age":16}
    
    #jsondata = json.dumps(data,ensure_ascii=False)
    jsondata = json.dumps(data)
    print("data convert to json")
    print type(json)
    text = json.loads(jsondata)
    print("json convert to data")
    print text["username"]
    print text["age"]
    
    

    使用第三方库:Demjson

      Demjson 是 python 的第三方模块库,可用于编码和解码 JSON 数据,包含了 JSONLint 的格式化及校验功能。

     函数定义:

     源码解析:

    #!/usr/bin/python
    import demjson
    
    data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ] 
    
    json = demjson.encode(data)
    print json
    
    text = demjson.decode(json)
    print  text
    
    

    参考文档

    1 [案例]: https://www.runoob.com/python/python-json.html

  • 相关阅读:
    常见模块和包
    二分查找算法
    常见内置函数
    Django总目录
    nginx配置站点
    Arduino语言
    Python连接Arduino的方法
    机器人学习
    Redis
    arduino总目录
  • 原文地址:https://www.cnblogs.com/dylancao/p/12052811.html
Copyright © 2011-2022 走看看