Reputation: 376
I have a python list of objects which looks like so
[
<NodeImage: id=aki-00501552, name=ubuntu/kernels-testing/ubuntu-lucid-amd64-linux-image-2.6.32-341-ec2-v-2.6.32-341.42-kernel, driver=Amazon EC2 (ap-southeast-1) ...>,
<NodeImage: id=aki-00c4bd52, name=ubuntu-kernels/ubuntu-lucid-amd64-linux-image-2.6.32-316-ec2-v-2.6.32-316.31-kernel, driver=Amazon EC2 (ap-southeast-1) ...>,
<NodeImage: id=aki-015d1253, name=RH-pv-grub-hd00-V1.01-x86_64, driver=Amazon EC2 (ap-southeast-1) ...>, <NodeImage: id=aki-01f58a53, name=None, driver=Amazon EC2 (ap-southeast-1) ...>
]
I want to convert this to JSON format which will look like so,
[
{
"id":"aki-00501552", "name":"ubuntu/kernels-testing/ubuntu-lucid-amd64-linux-image-2.6.32-341-ec2-v-2.6.32-341.42-kernel","driver":"Amazon EC2 (ap-southeast-1)"
},
{
"id":"aki-00c4bd52", "name":"ubuntu-kernels/ubuntu-lucid-amd64-linux-image-2.6.32-316-ec2-v-2.6.32-316.31-kernel", "driver":"Amazon EC2 (ap-southeast-1)"
},
{
"id":"aki-015d1253", "name":"RH-pv-grub-hd00-V1.01-x86_64", "driver":"Amazon EC2 (ap-southeast-1)"
}
]
Is there a way to do this conversion.
Upvotes: 0
Views: 1249
Reputation: 114481
If the data is just an array of objects containing strings/numbers and other json-compatible values you can just use:
s = json.dumps([x.__dict__ for x in data])
In Python x.__dict__
is a dictionary that contains all data members of object x
.
Upvotes: 1