简体   繁体   English

如何将python openstack对象打印为json

[英]How to print python openstack object as json

I'm trying to print a python object as json using json.dumps() 我正在尝试使用json.dumps()将python对象打印为json

The object is a tenant object from keystoneclient.v2_0.client module. 该对象是来自keystoneclient.v2_0.client模块的租户对象。

If I print the object directly I get: 如果直接打印对象,则会得到:

<Tenant {u'description': u'', u'enabled': True, u'id': u'dea3061f17df49a1a22f105d5e9bc971', u'name': u'Tets Lab 01'}>

Passing it to json.dumps fails ie 将其传递给json.dumps失败,即

my_tenant = keystone.tenants.get('dea3061f17df49a1a22f105d5e9bc971')
json.dumps(my_tenant)

The error indicates that it is not serializable File "/usr/lib/python2.7/json/encoder.py", line 178, in default raise TypeError(repr(o) + " is not JSON serializable") 错误表明它不可序列化,文件“ /usr/lib/python2.7/json/encoder.py”,第178行,默认情况下引发TypeError(repr(o)+“不可JSON可序列化”)

Other than parsing the string returned from the object, does anyone know if a way I can easily convert this to JSON output? 除了解析从对象返回的字符串之外,还有谁知道我是否可以轻松地将其转换为JSON输出的方法?

I ended up going through the code at: https://github.com/openstack/python-keystoneclient 我最终通过以下代码查看了代码: https : //github.com/openstack/python-keystoneclient

The Tenant class extends a base resource, which implements a to_dict() method. Tenant类扩展了基础资源,该基础资源实现了to_dict()方法。 This returns the data in a json format. 这将以json格式返回数据。 https://github.com/openstack/python-keystoneclient/blob/master/keystoneclient/openstack/common/apiclient/base.py https://github.com/openstack/python-keystoneclient/blob/master/keystoneclient/openstack/common/apiclient/base.py

my_tenant = keystone.tenants.get('dea3061f17df49a1a22f105d5e9bc971')
json.dumps(my_tenant.to_dict())

这应该做

json.dumps(vars(my_tenant))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM