JSON of serialization and deserialization

Keywords: Python JSON xml Programming


To transfer objects between different programming languages, you need to serialize them into a standard format, such as XML
But a better way is to serialize it into JSON, because JSON represents a string that can be read by all languages, stored on disk or transmitted over the network easily
JSON is not only standard format, but also faster than XML, and can be read directly in Web pages, because the object represented by JSON is the object of standard JavaScript language

The built-in data types of JSON and Python correspond to the following:

JSON type Python type
{} dict
[] list
"string" str
1234.56 int or float
true/false True/False
null None


 

 

 

 

 

 

 

 

Example

import json

d = dict(name='Bob', age=20, score=88) ##dict objects can be serialized directly to {} of JSON
print(json.dumps(d)) ##The dumps() method returns the standard JSON string format of the object. Similarly, the dump() method can directly write JSON to a file like object

json_str = '{"age": 20, "score": 88, "name": "Bob"}' 
print(json.loads(json_str)) ##loads() or the corresponding load() method, the former deserializes the JSON string, the latter reads the string from the file like object and deserializes it


##################################################################################################################    


import json

class Student(object):
  def __init__(self, name, age, score):
    self.name = name
    self.age = age
    self.score = score

def student2dict(std):
  return {
    'name': std.name,
    'age': std.age,
    'score': std.score
  }

def dict2student(d):
  return Student(d['name'], d['age'], d['score'])

s = Student('Bob', 20, 88)

#Student Object is not directly accessible dumps Method transformation json Need to be converted into dict
print(json.dumps(s, default=student2dict)) 

#In this way, any class Convert to dict
#usually class There is one instance of__dict__Property, which is a dict,Used to store instance variables. There are a few exceptions, such as the definition__slots__Of class
print(json.dumps(s, default=lambda obj: obj.__dict__)) 

#loads()Method first converts to a dict Object, and then, the object_hook Function is responsible for dict Convert to Student
json_str = '{"age": 20, "score": 88, "name": "Bob"}'
print(json.loads(json_str, object_hook=dict2student))

 

Note: since the JSON standard specifies that JSON encoding is UTF-8, we can always convert Python str to JSON strings correctly

Posted by marty_arl on Fri, 06 Dec 2019 15:27:24 -0800