1. Serializing and deserializing with a JSON module
Note: The file suffix name obtained with JSON serialized data type must be JSON. Because if it's not a JSON suffix, nobody else knows it's a JSON serialized file.
Serialization: Json.dumps (an object that needs to be converted to a string), converts the data type to a string, and does not save to a file.
Import jsondicts = {' roles ': [ {' role ': ' Saber ', ' name ': ' Dapeng ', ' life ': ' {'} ', ' role ': ' Shengqi ', ' name ': ' Archer ', ' Life ': $ ]}f = open (' 111.json ', ' w ') d = json.dumps (dicts) print (D,type (d)) # {"Roles": [{"Role": "Saber", " Name ":" "Dapeng", "Life": $ {"Role": "Shengqi", "Name": "Archer", "Life": $}]} <class ' str ' >
Serialization: Json.dump (obj, file) converts a data type to a city string while also depositing it into a file.
Import jsondicts = {' roles ': [ {' role ': ' Saber ', ' name ': ' Dapeng ', ' life ': ' {'} ', ' role ': ' Shengqi ', ' name ': ' Archer ', ' Life ': $ ]}f = open (' 111.json ', ' w ') d = json.dump (dicts,f) print (D,type (d))
2 deserialization of Json.loads (String object)
Dicts = {' roles ': [ {' role ': ' Saber ', ' name ': ' Dapeng ', ' life ': ' {'} ', ' role ': ' Shengqi ', ' name ': ' Archer ', ' Life ': $ ]}import jsond = json.dumps (dicts) print (Json.loads (d))
Json.load (File object) converts a string in a file into a type such as a dictionary.
Import jsonf = open (' 111.json ', ' R ') print (Json.load (f))
3.json.dumps () and Json.loads () are only in memory, not stored in the hard disk, what is the meaning of existence?
① put your memory data through the network and send it to other people for sharing. A network share can only be sent in string format, so it is converted to a string format using Json.dumps.
② defines the rules of interaction between different languages.
1. Plain text disadvantage: You cannot share complex data types, such as nesting.
2.xml disadvantage: Occupy a large space (such as <year>2018</year>, while the dictionary can be used ' year ': 2018, more space-saving)
3.json simple, good readability, low memory consumption
4.json.dump () dump multiple times can.
Import jsonf = open (' 112.json ', ' w ') a = [1,2,3,4,5]b = {1:2,2:3,3:4,4:5,5:6}json.dump (a,f) json.dump (b,f)
So can load be multiple times?
Dump multiple files, can not load one or more times.
Import jsonf = open (' 112.json ', ' R ') Json.load (f)
Serializing JSON modules