how can I create a class and decode/encode as json?

Denis McMahon denismfmcmahon at gmail.com
Tue Jan 13 13:02:43 EST 2015


On Tue, 13 Jan 2015 08:17:18 -0800, robertchen117 wrote:

> I want to send Message to rabbitmq and receive from rabbitmq, message
> format is below.
> 
> how can I create a class and decode/encode as json?

It may be easier to use dictionaries than classes.

>>> import json
>>> thing = {}
>>> thing["message"] = {}
>>> thing["message"]["dateCreated"] = "1417713299"
>>> thing["message"]["operations"] = []
>>> for i in range(3):
...     bit = {}
...     bit["sequence"] = i
...     bit["data"] = "blah blah blah"
...     thing["message"]["operations"].append(bit)
... 
>>> json.dumps(thing)
'{"message": {"operations": [{"data": "blah blah blah", "sequence": 0}, 
{"data": "blah blah blah", "sequence": 1}, {"data": "blah blah blah", 
"sequence": 2}], "dateCreated": "1417713299"}}'

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list