将动态python对象转换为json [英] Convert dynamic python object to json

查看:124
本文介绍了将动态python对象转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
Python可序列化的对象json

Possible Duplicate:
Python serializable objects json

我需要知道如何将动态python对象转换为JSON.该对象必须能够具有多个级别的对象子对象.例如:

I need to know how to convert a dynamic python object into JSON. The object must be able to have multiple levels object child objects. For example:

class C(): pass
class D(): pass

c = C()
c.dynProperty1 = "something"
c.dynProperty2 = { 1, 3, 5, 7, 9 }
c.d = D()
c.d.dynProperty3 = "d.something"

# ... convert c to json ...

使用python 2.6以下代码:

Using python 2.6 the following code:

import json

class C(): pass
class D(): pass

c = C()
c.what = "now?"
c.now = "what?"
c.d = D()
c.d.what = "d.what"

json.dumps(c.__dict__)

产生以下错误:

TypeError: <__main__.D instance at 0x99237ec> is not JSON serializable

我不知道用户可能将什么类型的子对象放入c中.是否有足够聪明的解决方案来检测属性是否为对象并自动解析为__dict__?

I don't know what types of subobjects a user might put into c. Is there a solution that is smart enough to detect if an attribute is an object and parse it's __dict__ automatically?

已更新以包含c上的子对象.

推荐答案

指定default=参数(

Specify the default= parameter (doc):

json.dumps(c, default=lambda o: o.__dict__)

这篇关于将动态python对象转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆