Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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

like image 794
softwarematter Avatar asked May 02 '13 02:05

softwarematter


2 Answers

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"]}
like image 200
hek2mgl Avatar answered Sep 20 '22 06:09

hek2mgl


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)
like image 32
Zahran Avatar answered Sep 19 '22 06:09

Zahran