Ask Your Question

How to format a python __str__ output

asked 2015-05-20 22:35:35 -0500

xiangfeiz gravatar image

This is probably a basic python programming question.

I see a lot of object written to a long line of string in log file. E.g.

vol={'migration_status': None, 'availability_zone': u'nova', 'terminated_at': None, 'updated_at': datetime.datetime(2015, 5, 15, 7, 0, 11), 'provider_geometry': None, 'snapshot_id': None, 'ec2_id': None, 'mountpoint': u'/dev/sdb', 'deleted_at': None, 'id': u'83a5ade7-275e-4ffd-b494-a4c2c9a169d1', 'size': 10L, 'user_id': u'2b5cd66674d24c4f94138002d96f5f96', 'attach_time': u'2015-05-13T06:12:35.749100', 'attached_host': None, 'display_description': None, 'volume_admin_metadata': [, ], 'encryption_key_id': None, 'project_id': u'9ba90732bdba43dcbd49e111cbe92458', 'launched_at': datetime.datetime(2015, 5, 13, 5, 56, 33), 'scheduled_at': datetime.datetime(2015, 5, 13, 5, 56, 31), 'status': u'available', 'volume_type_id': None, 'deleted': False, 'provider_location': None, 'host': u'controller01', 'source_volid': None, 'provider_auth': None, 'display_name': u'parallel_200_1-my_vol107-umrnk5jchjwo', 'instance_uuid': u'a81b355d-d240-4888-93a1-7e10822a777f', 'bootable': False, 'created_at': datetime.datetime(2015, 5, 13, 5, 56, 31), 'attach_status': u'attached', 'volume_type': None, '_name_id': None, 'volume_metadata': [], 'metadata': {u'readonly': u'False', u'attached_mode': u'rw'}}

I want to have a way to format this output to a json-like format to be more readable. Something like:

      'migration_status': None, 
      'availability_zone': u'nova', 

How could I do that?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2015-05-21 02:16:05 -0500

Ranjit gravatar image

you can use json module to do this like below:

>>> import json
>>> vol={'migration_status': None, 'availability_zone': u'nova'}
>>> a=json.dumps(vol, sort_keys=True, indent=4)
>>> str ='\n'.join([l.rstrip() for l in  a.splitlines()])
>>> print str
    "availability_zone": "nova",
    "migration_status": null

See the help for json module by using help(json)
edit flag offensive delete link more

Get to know Ask OpenStack

Resources for moderators

Question Tools

1 follower


Asked: 2015-05-20 22:35:35 -0500

Seen: 168 times

Last updated: May 21 '15