Home > Backend Development > Python Tutorial > How to use python json module

How to use python json module

silencement
Release: 2019-06-24 11:29:07
Original
2525 people have browsed it

How to use python json module

JSON (JavaScript Object Notation, JS object tag) is a lightweight data exchange format. The data format of JSON is actually the dictionary format in python, which can contain arrays enclosed in square brackets, which are lists in python.

In python, there are modules that specifically handle json format - json and picle modules

The Json module provides four methods: dumps, dump, loads, load

The pickle module also provides four functions: dumps, dump, loads, load

1. dumps and dump:

dumps and dump Serialization method

dumps has only been completed Serialize to str,

dump must pass the file descriptor, and save the serialized str to the file

View source code:

def 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``.
    # 序列号 “obj” 数据类型 转换为 JSON格式的字符串 
def 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).
Copy after login

Sample code:

>>> import json
>>> json.dumps([])    # dumps可以格式化所有的基本数据类型为字符串
'[]'
>>> json.dumps(1)    # 数字
'1'
>>> json.dumps('1')   # 字符串
'"1"'
>>> dict = {"name":"Tom", "age":23}  
>>> json.dumps(dict)     # 字典
'{"name": "Tom", "age": 23}'
Copy after login
a = {"name":"Tom", "age":23}
with open("test.json", "w", encoding='utf-8') as f:
    # indent 超级好用,格式化保存字典,默认为None,小于0为零个空格
    f.write(json.dumps(a, indent=4))
    # json.dump(a,f,indent=4)   # 和上面的效果一样
Copy after login

2. loads and load

loads and load Deserialization method

loads only completes deserialization,

load only receives file descriptors, completed Reading files and deserializing

View source code:

def 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`` instance containing a JSON document) to a Python object.
       将包含str类型的JSON文档反序列化为一个python对象"""
def 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格式数据的可读文件饭序列化为一个python对象"""
Copy after login

Example:

>>> json.loads('{"name":"Tom", "age":23}')
{'age': 23, 'name': 'Tom'}
Copy after login
import json
with open("test.json", "r", encoding='utf-8') as f:
    aa = json.loads(f.read())
    f.seek(0)
    bb = json.load(f)    # 与 json.loads(f.read())print(aa)print(bb)# 输出:{'name': 'Tom', 'age': 23}
{'name': 'Tom', 'age': 23}
Copy after login

The above is the detailed content of How to use python json module. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template