zoukankan      html  css  js  c++  java
  • 18.Python JSON

    Python 语言来编码和解码 JSON 对象

    JSON 函数

    python中使用JSON函数需要导入json库:import json。

    json中的函数有:json.dumps和json.loads

    json.dumps将Python对象编码成JSON字符创

    json.loads将JSON字符串解码为python对象

    以下实例将数组编码为 JSON 格式数据:

    import json
    data = { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 }
    print(json.dumps(data))  

    结果:

    {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
    

    使用参数让 JSON 数据格式化输出:

    import json
    data = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
    print(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': ')))
    

    结果:

    {
        "a": 1,
        "b": 2,
        "c": 3,
        "d": 4,
        "e": 5
    }
    

    以下实例展示了Python 如何解码 JSON 对象:

    import json
    data = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
    print(json.loads(data))
    

    结果:

    {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
    

      

    python类型向json类型转化对照表:

    python json    
    dict object
    list,tuple array
    str,unicode string           
    int,long,float number
    True true
    False false                  
    None null      

    json类型向python类型转化对照表:

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

      

    除了可以使用内置的 json 模块外,还可以使用第三方库Demjson转换

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

    本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    C++ 编译时字符串加密
    c#自动修复缺损和不规范的html
    C#下载网络资源(网页或文件)
    yum install 命令下载安装离线包
    C# Sql Server 数据库 传递 表值参数
    cximage 裁剪图片并背景透明
    centos 7.5 编译并运行 opencv 4.5.1 c++
    c++ freeimage 指定颜色透明
    c++ string 大小写转换
    opencv 裁剪图像
  • 原文地址:https://www.cnblogs.com/zhangan/p/14743839.html
Copyright © 2011-2022 走看看