Johannes Johannes - 1 year ago 61
JSON Question

How can I pack different lists and dicts into a single JSON object in python

I have a set of different lists and dictionaries and variables.
Can I pack them all into one JSON object?
How would you go about it?
Call json.dumps() on each of them and then somehow put them together?

(My purpose behind this is to make the data available to my jacascript programm via npm python shell.)

thank you

Answer Source

Just put all your individual lists and dicts into one big dictionary and json.dumps that dictionary. You could use the variable names as keys, or just put them all one after the other in a list.

>>> a_list = [1,2,3]
>>> a_dict = {"foo": 42, "bar": [4,5,6]}
>>> import json
>>> everything = {"a_list": a_list, "a_dict": a_dict}
>>> json.dumps(everything)
'{"a_list": [1, 2, 3], "a_dict": {"foo": 42, "bar": [4, 5, 6]}}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download