How to generate a json file in python from nested array/dictionary/object

I need to generate a json file like:

  "messages":["msg 1","msg 2","msg 3"]

The data in this file should be populated from various places. What is the best way to do this in python? I can always write as a text file (character by character). But I was wondering if there is a cleaner way by which an array could be created and use some library methods to generate this json file. Please suggest a good solution

PS. I am new to python

Best answer

You can use json.dumps() for that. You can pass a dictionary to it and the function will encode it as json.


import json

# example dictionary that contains data like you want to have in json
dic={'age': 100, 'name': '', 'messages': ['msg 1', 'msg 2', 'msg 3']}

# get json string from that dictionary
print json


{"age": 100, "name": "", "messages": ["msg 1", "msg 2", "msg 3"]}