SoFunction
Updated on 2025-04-13

Python json serialization interpretation

json module

  • JSON: is a lightweight data exchange format, a data format independent of programming languages.
  • The data format is simple and clear. Easy to transmit data between networks.

json serialization basic usage

Serialization

  • Convert objects in Python to strings in JSON format
import json
ls = [{"name": "Zhang San", "age": 20}, {"name": "Li Si", "age": 22}]
jsonstr = (ls)
print(jsonstr)

Parameters in dumps method

  • skipkeys: The keys in JSON only support strings, numbers, booleans, and null representations. If an unsupported key type is provided in python, skipkeys must be set to True
ls = [{"name": "Zhang San", "age": 20, (1,2): 100, None: 1}, {"name": "Li Si", "age": 22}]
jsonstr = (ls, skipkeys=True)
print(jsonstr)
  • ensure_ascii: Unicode encoding of data outside ascii. If you want not to encode, you can set it to False
ls = [{"name": "Zhang San", "age": 20, (1,2): 100, None: 1}, {"name": "Li Si", "age": 22}]
jsonstr = (ls, skipkeys=True, ensure_ascii=False)
  • indent: Beautify json, the value is a number, recommended to use 4
  • allow_nan: Whether to support non-numeric float("nan"), positive infinite float("inf"), negative infinite float("-inf") for serialized data
  • default: Special processing can be performed on objects that cannot be serialized (default function calls will be triggered during serialization).
import json

class Person:
    def __init__(self, name, age):
         = name
         = age


if __name__ == '__main__':
 
    p1 = Person(name="Zhang San", age=20)    # p1.__dict__ : You can get the dictionary representation of an object.    p2 = Person(name="Li Si", age=21)
    p3 = Person(name="Wang Wu", age=22)
    p4 = Person(name="Zhao Liu", age=20)
    person_list = [p1, p2, p3, p4]
    # Use JSON serialization to convert data into JSON strings    json_string = (person_list, ensure_ascii=False, default=lambda obj: obj.__dict__, indent=2)

    print(json_string)
  • cls: Allows to define a class that requires inheritance and override the default method in the parent class to solve the problem that data cannot be serialized.
from datetime import date, datetime

class Person:
    def __init__(self, name, age, birth=None):
         = name
         = age
         = birth


class JsonEncoder():
    def default(self, o):
        if hasattr(o, "__dict__"):
            return o.__dict__
        if isinstance(o, date):
            return ('%Y-%m-%d')

        if isinstance(o, datetime):
            return ('%Y-%m-%d %H:%M:%S')

        return str(o)


if __name__ == '__main__':
    p1 = Person(name="Zhang San", age=20, birth=date(2000, 10, 10))
    print(p1.__dict__)
    p2 = Person(name="Li Si", age=21)
    p3 = Person(name="Wang Wu", age=22)
    p4 = Person(name="Zhao Liu", age=20)
    person_list = [p1, p2, p3, p4]
    # Use JSON serialization to convert data into JSON strings    json_string = (person_list, ensure_ascii=False, cls=JsonEncoder, indent=2)

    print(json_string)
  • loads(string , object_hook=None)
import json
from datetime import date, datetime

# Create a string in json formatstring = '[{"name": "Zhang San", "age": 20, "birth": "1990-10-10"}, {"name": "Li Si", "age": 20, "birth": "1990-10-10"}]'


class Person:
    def __init__(self, name, age, birth=None):
         = name
         = age
         = birth

    def __repr__(self):
        return str(self.__dict__)


def test(kwargs):
    if "birth" in kwargs:
        kwargs["birth"] = (kwargs["birth"], '%Y-%m-%d').date()

    return Person(**kwargs)


# Convert this string to a listls = (string, object_hook=test)

print(ls)

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.