Python

Python基础(32) - 将类的实例转换成JSON字符串

2020-03-07  本文已影响0人  xianling_he

将类的实例转换成JSON字符串

将一个对象类型转换成JSON字符串

import json


class Product:
    def __init__(self,name,price,count):
        self.name = name
        self.price = price
        self.count = count


product = Product('iPhonex',5000,3)
def productToDict(obj):
    return{
        'name':obj.name,
        'price':obj.price,
        'count':obj.count
    }
jsonStr = json.dumps(product,default=productToDict,ensure_ascii=False)
print(jsonStr)
hexianling.png

完整代码如下:

class Product:
    def __init__(self,name,price,count):
        self.name = name
        self.price = price
        self.count = count


product = Product('iPhonex',5000,3)

def productToDict(obj):
    return{
        'name':obj.name,
        'price':obj.price,
        'count':obj.count
    }

jsonStr = json.dumps(product,default=productToDict,ensure_ascii=False)
print(jsonStr)

将转换函数返回的JSON串,重新转换成JSON类型字符串

class Product:
    def __init__(self,d):
        self.__dict__ = d #将属性传给构建的字典
f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\03-数据存储\\files\\product.json','r')
jsonStr1 = f.read()
products1 = json.loads(jsonStr1,object_hook= Product)
print(products1)
jsonStrNew = json.dumps(products1,default=productToDict,ensure_ascii=False)
print(jsonStrNew)

完整代码如下:

import json
def productToDict(obj):
    return{
        'name':obj.name,
        'price':obj.price,
        'count':obj.count
    }

class Product:
    def __init__(self,d):
        self.__dict__ = d #将属性传给构建的字典

f = open('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\03-数据存储\\files\\product.json','r')
jsonStr1 = f.read()
hexianling.png

总结

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

加油 2020-3-7

上一篇 下一篇

猜你喜欢

热点阅读