42-- instance of a class is to convert the string json

1. Convert the object corresponding to a character string json

import json

class Product:
    def __init__(self, name, price, count):
        self.name = name
        self.price = price
        self.count = count
        
product = Product('特斯拉', 1000000, 20)
def product2Dict(obj):
    return {
        'name': obj.name,
        'price':obj.price,
        'count':obj.count
    }
jsonStr = json.dumps(product, default=product2Dict, ensure_ascii=False)
print(jsonStr)
{"name": "特斯拉", "price": 1000000, "count": 20}

2. Convert the list of objects to json array

f = open('products.json', 'r', encoding='utf-8')
jsonStr = f.read()
f.close()

class Product:
    def __init__(self, d):
        self.__dict__ = d
        
products = json.loads(jsonStr, object_hook=Product)
print(products)

for product in products:
    print(product.name)

jsonStr = json.dumps(products, default=product2Dict, ensure_ascii=False)
print(type(jsonStr))
print(jsonStr)
[<__main__.Product object at 0x00000161832F02E8>, <__main__.Product object at 0x00000161832F0FD0>]
iPhone9
特斯拉
<class 'str'>
[{"name": "iPhone9", "price": 9999, "count": 3000}, {"name": "特斯拉", "price": 800000, "count": 122}]

43 - Operation SQLite database

Ruo
Published 160 original articles · won praise 181 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_29339467/article/details/104613739