• python学习笔记——python JSON


    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。

    1、JSON 函数

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

    函数描述
    json.dumps 将 Python 对象编码成 JSON 字符串
    json.loads 将已编码的 JSON 字符串解码为 Python 对象

    (1)json.dumps

    json.dumps 用于将 Python 对象编码成 JSON 字符串。

    语法

    json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", default=None, sort_keys=False, **kw)

    举例:

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

    执行结果:

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

    python 原始类型向 json 类型的转化对照表:

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

    (2)json.loads

    json.loads 用于解码 JSON 数据。该函数返回 Python 字段的数据类型。

    语法

    json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

    举例:

    #coding: utf-8
    import json
    
    json_str = """
    {
        "id" : 1,
        "name" : "python"
    }
    """
    res = json.loads(json_str)
    
    print res
    print(res['id']) # 1
    print(res['name']) # python

    执行结果:

    {u'id': 1, u'name': u'python'}
    1
    python

    json 类型转换到 python 的类型对照表:

    JSONPython
    object dict
    array list
    string unicode
    number (int) int, long
    number (real) float
    true True
    false False
    null None
  • 相关阅读:
    html{-webkit-text-size-adjust:none;}(取消浏览器最小字体限制)
    移动端最小字体限制测试
    关键字(1)
    常用函数(1)
    新建体(2):create or replace object创建存储包、存储过程、函数
    关键字(5):cursor游标:(循环操作批量数据)
    关键字(6):trigger触发器
    新建体(1):新建type
    rownum查询前N条记录
    表连接join on
  • 原文地址:https://www.cnblogs.com/pachongshangdexuebi/p/8509720.html
Copyright © 2020-2023  润新知