Skip to content

将对象列表转换为JSON数组 #73

@Sogrey

Description

@Sogrey
import json

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

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))

json模块的dumps用于将对象转换为JSON字符串,通过default参数指定一个转换函数,可以在该函数中提取对象的属性值,并生成JSON对象,最后dumps负责将转换函数返回的JSON对象转换为JSON字符串。

如何将一个JSON文档映射为对象 #71
将一个对象转换为对应的JSON字符串 #72

Metadata

Metadata

Assignees

No one assigned

    Labels

    数据存储文件存储,数据库存储

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions