066 json module

Json

  • A program written in python, using java to write a program, the program requires two exchanges between the data, a predetermined common data types of languages, JSON string

1. Serialization

The objects (variables) into or from the memory may store the serialization process is called

Serialization advantages:

  1. Persist status: Memory is not permanently stored data, when the program runs for some time, we power down or restart the program, in-memory data on the program for some time before the (structured) have been cleared. But before power off or restart the program that are currently all the data in memory are saved (saved to a file) to perform data can be loaded from the file before the program to the next, and then continue, which is serialized .
  2. Cross-platform data exchange: not only the contents of the serialized write serialization disk, you can also transmitted over the network to another machine, if the two sides agreed to send and receive good practical one sequence of the format, then it broke platform / language difference limit brought achieve a cross-platform data exchange.

2.json serialization

Json serialization is not unique to python, json serialization in java and other languages ​​will be involved, so use json serialization can achieve the purpose of cross-platform data transmission.

  • json data types and data type correspondence table python

    Json type Python type
    {} dict
    [] list
    "string" str
    520.13 int or float
    true/false True/False
    null None
  • json module serialization and deserialization of a process as shown in FIG.

    json module

3. Examples sequence deserialization

  • Take for example the dictionary
# 序列化:从python的字典(最常用)变成json串, dump
# 反序列化:从json串变成python的字典(最常用),load

import json

dic = {'a': 1, 'b': 'abc', 'c': None}

data = json.dumps(dic)  # 序列化到内存中
print(data,type(data))  # 单引号全部变成双引号
# {"a": 1, "b": "abc", "c": null} <class 'str'>

data = json.loads(data)  # 从内存中获取json串
print(data,type(data))# 双引号全都变成了单引号
# {'a': 1, 'b': 'abc', 'c': None} <class 'dict'>

with open('test.json','w',encoding='utf8') as fw:# 还可以直接序列化写在文件里
    json.dump(dic,fw)

with open(f'{"test"}.json','r',encoding='utf8') as fr: # 直接从文件里取,进行反序列
    data = json.load(fr)
    print(data)
    # {'a': 1, 'b': 'abc', 'c': None}

Guess you like

Origin www.cnblogs.com/xichenHome/p/11366349.html