Python Daily Practice - Data Storage Level 4: How to Convert a Python Object to a Corresponding JSON String

The fourth level of the interview question:

Part 1 - Test Site:

  • Usage of dumps function.

Part 2 - Interview Questions:

1. Interview question 1: Convert a Python object to the corresponding JSON string.

2. Interview question 2: Convert a list of objects to a JSON array.


Part 3 - Analysis:

One of the interview questions converts a Python object to the corresponding JSON string:

  • Using the dumps() function, the key point is to use the conversion function~
# coding=utf-8
# _author__ = 孤寒者
import json


class Product:
    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height

product = Product('孤寒者', 18, 130)

def product2Dict(obj):
    return {
    
    
        'name': obj.name,
        'age': obj.age,
        'height': obj.height
    }

# dumps()方法的default参数指定转换函数。                
jsonStr = json.dumps(product, default=product2Dict, ensure_ascii=False)
print(jsonStr)
print(type(jsonStr))

insert image description here

Interview question 2 converts a list of objects to a JSON array:

  • In order to implement this function, we need a list of objects, so we convert the JSON document (the test.json file below) to a list of objects (we already know how to operate it in the previous question~), and then convert it to JSON array.
[
  {
    
    
    "name": "孤寒者",
    "age": 18,
    "height": 130
  },
  {
    
    
    "name": "小张",
    "age": 18,
    "height": 80
  }
]
# coding=utf-8
# _author__ = 孤寒者
import json

class Product:
    def __init__(self, d):
        self.__dict__ = d

with open('test.json', 'r', encoding='utf-8') as f:
    jsonStr = f.read()
    products = json.loads(jsonStr, object_hook=Product)
    print(products)

insert image description hereThe screenshot above shows that we have indeed converted the JSON document into a list of objects.
Let's start solving the problem:

# coding=utf-8
# _author__ = 孤寒者
import json

class Product:
    def __init__(self, d):
        self.__dict__ = d

with open('test.json', 'r', encoding='utf-8') as f:
    jsonStr = f.read()
    products = json.loads(jsonStr, object_hook=Product)
    print(products)
    for product in products:
        print(product.name)

    print("*"*25)
    
    # 解题部分:
    def product2Dict(obj):
        return {
    
    
            'name': obj.name,
            'age': obj.age,
            'height': obj.height
        }

    jsonStr = json.dumps(products, default=product2Dict, ensure_ascii=False)
    print(jsonStr)
    print(type(jsonStr))

insert image description here


Part 4 - Conclusion:

  • The dumps function of the json module is used to convert objects to JSON strings.
  • Specify a conversion function through the default parameter, in which the attribute value of the object can be extracted, and a JSON object can be generated. Finally, dumps is responsible for converting the JSON object returned by the conversion function into a JSON string.

Guess you like

Origin blog.csdn.net/qq_44907926/article/details/123019162