zoukankan      html  css  js  c++  java
  • JSON模块

    JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式。

    JSON模块属于Python的标准库,在安装python时会被默认安装,使用时直接import即可,无需单独安装。

    Python可以使用 json 模块来对 JSON 数据进行编解码。

    先看看帮助文档:

    >>> import json
    >>> dir(json)
    ['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_default_decoder', '_default_encoder', 'codecs', 'decoder', 'detect_encoding', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']
    

    JSON模块包括两个常用的内置函数:

    • json.dumps():对数据进行编码,序列化。将python对象编码为json字符串。
    • json.loads():对数据进行解码,反序列化。将json字符串解码为python对象。

    在json的编解码过程中,python的原始类型与json类型会相互转换。

    Python 编码为 JSON 类型转换对应表:

    JSON 解码为 Python 类型转换对应表:

    用法如下,文档太长参数说明太多,这里只贴了语法格式部分:

    >>> help(json.dumps)
    Help on function dumps in module json:
    
    dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
        Serialize ``obj`` to a JSON formatted ``str``.
    
    >>> help(json.loads)
    Help on function loads in module json:
    
    loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
        Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object.
    
    If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised.
    

    注意上述文档说的是str,也就是这两个方法操作的是JSON格式的字符串。

    示例:

    >>> users=[{'name':'keith','age':18,'tel':110},{'name':'jerry','age':36,'tel':112}]
    >>> import json
    
    >>> j=json.dumps(users)
    >>> j
    '[{"name": "keith", "age": 18, "tel": 110}, {"name": "jerry", "age": 36, "tel": 112}]'
    
    >>> users2=json.loads(users_json)
    >>> users2
    [{'name': 'keith', 'age': 18, 'tel': 110}, {'name': 'jerry', 'age': 36, 'tel': 112}]
    

    默认的格式并不美观,常见的JSON文档都是带缩进的,这里当然也可以,json.dumps()提供了可选参数。

    >>> print(json.dumps(users,sort_keys=True, indent=4, separators=(',', ': ')))
    [
        {
            "age": 18,
            "name": "keith",
            "tel": 110
        },
        {
            "age": 36,
            "name": "jerry",
            "tel": 112
        }
    ]
    
    If indent is a non-negative integer or string, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, negative, or "" will only insert newlines. None (the default) selects the most compact representation. Using a positive integer indent indents that many spaces per level. If indent is a string (such as "	"), that string is used to indent each level.
    缩进是一个非负整数或字符串,默认为None。
    
    If specified, separators should be an (item_separator, key_separator) tuple. The default is (', ', ': ') if indent is None and (',', ': ') otherwise. To get the most compact JSON representation, you should specify (',', ':') to eliminate whitespace.
    分隔符是一个元祖, 包含两个元素,一个是item分隔符,一个是kv分隔符。默认为 (', ', ': ')。
    
    If sort_keys is true (default: False), then the output of dictionaries will be sorted by key.
    sort_keys如果为true,则输出的字典会以key排序。默认为False。
    

    如果你要处理的是文件而不是字符串,可以使用json.dump()json.load()来编码和解码JSON数据。

    >>> help(json.dump)
    Help on function dump in module json:
    
    dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
        Serialize ``obj`` as a JSON formatted stream to ``fp`` (a ``.write()``-supporting file-like object).
    
    >>> help(json.load)
    Help on function load in module json:
    
    load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
        Deserialize ``fp`` (a ``.read()``-supporting file-like object containing a JSON document) to a Python object.
    

    示例:

    写入JSON数据
    with open('data.json', 'w') as f:
        json.dump(data, f)
    
    读取数据
    with open('data.json', 'r') as f:
        data = json.load(f)
    
    >>> with open('data.json', 'w') as f:
    ... 	 json.dump([{'name':'keith','age':18,'tel':110},{'name':'jerry','age':36,'tel':112}], f)
    ... 
    # cat data.json
    [{"name": "keith", "age": 18, "tel": 110}, {"name": "jerry", "age": 36, "tel": 112}]
    
    >>> with open('data.json', 'r') as f:
    ... 	data = json.load(f)
    ...
    >>> data
    [{'name': 'keith', 'age': 18, 'tel': 110}, {'name': 'jerry', 'age': 36, 'tel': 112}]
    

    参考:
    https://docs.python.org/3/library/json.html
    http://www.runoob.com/python/python-json.html
    http://www.runoob.com/python3/python3-json.html

  • 相关阅读:
    Beetl模板 [记录]
    wx 小程序开发 [记录]
    高德定位获取省市区[记录]
    vue 学习记录 [记录]
    正则表达+验证 [记录]
    倒计时60s短信 [记录]
    @media [记录]
    JSON + Ajax [记录]
    Webstorm [记录]
    JQ 组合代码 [记录]
  • 原文地址:https://www.cnblogs.com/keithtt/p/7633776.html
Copyright © 2011-2022 走看看