I need to generate a json file like:
{
"age":100,
"name":"mkyong.com",
"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
You can use json.dumps()
for that. You can pass a dictionary to it and the function will encode it as json.
Example:
import json
# example dictionary that contains data like you want to have in json
dic={'age': 100, 'name': 'mkyong.com', 'messages': ['msg 1', 'msg 2', 'msg 3']}
# get json string from that dictionary
json=json.dumps(dic)
print json
Output:
{"age": 100, "name": "mkyong.com", "messages": ["msg 1", "msg 2", "msg 3"]}
Try this out...
import json
with open('data.json', 'w') as outfile:
json.dump({
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}, outfile)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With