对象转json是python比较常见的一个应用场景,如何来实现呢?这里会涉及json
模块中的dumps
方法,具体操作如下:
- 导入json包
import json
- 自定义class
class Bill:
def __init__(self, billCode, sendOrgCode, recOrgCode, provinceName, cityName, countyName, address):
self.billCode = billCode
self.sendOrgCode = sendOrgCode
self.recOrgCode = recOrgCode
self.provinceName = provinceName
self.cityName = cityName
self.countyName = countyName
self.address = address
- 添加转json格式
def bill2dict(b):
return {
'billCode': b.billCode,
'sendOrgCode': b.sendOrgCode,
'recOrgCode': b.recOrgCode,
'provinceName': b.provinceName,
'cityName': b.cityName,
'countyName': b.countyName,
'address': b.address
}
- 调用dumps方法
result = json.dumps(bill, default=bill2dict)
- 打印结果
{"billCode": "518020062415", "sendOrgCode": "UC000277", "recOrgCode": "UC018145", "provinceName": "\u5317\u4eac", "cityName": "\u5317\u4eac\u5e02", "countyName": "\u897f\u57ce\u533a", "address": "111\u53d1\u9001\u5230"}
直接用
json.dumps(bill)
运行会报错,需自定义json格式。