Python 自定义对象数组 转JSON 字符串

前言

在Python中基本数据类型可以直接使用json.dumps直接转json字符串,但是对于自定义的类来说,需要先将对象“字典化”,也就是使用__dict__这个函数;同理对于数组中的对象,每个对象都需要提前“字典化”,废话不多说,看代码:

Report.py

class ReportBean:
    def __init__(self, channel, version, result):
        self.channel = channel
        self.version = version
        self.result = result


class ReportResultBean:
    def __init__(self, success, fail, total, startType, detail):
        self.success = success
        self.fail = fail
        self.total = total
        self.startType = startType
        self.detail = detail


class ReportResultDetailBean:
    def __init__(self, component, success):
        self.component = component
        self.success = success

TestJson.py

import json

from bean.Report import ReportResultBean, ReportResultDetailBean, ReportBean

bean = ReportResultDetailBean("com.onexzgj.Activity1", True).__dict__
bean1 = ReportResultDetailBean("com.onexzgj.Activity2", False).__dict__

details = []
details.append(bean)
details.append(bean1)

resultBean = ReportResultBean(100, 50, 150, "上架", details).__dict__

reportBean = ReportBean("应用宝", "第10000个版本", resultBean).__dict__

data2 = json.dumps(reportBean)

print(data2)

运行结果:

{"channel": "\u5e94\u7528\u5b9d", "version": "\u7b2c10000\u4e2a\u7248\u672c", "result": {"success": 100, "fail": 50, "total": 150, "startType": "\u4e0a\u67b6", "detail": [{"component": "com.onexzgj.Activity1", "success": true}, {"component": "com.onexzgj.Activity2", "success": false}]}}

格式化后如下所示:
Python 自定义对象数组 转JSON 字符串_第1张图片

你可能感兴趣的:(Python基础,python,python对象数据转json,python对象转json字符)