7

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

3
  • Use the builtin json library on your object... Commented May 2, 2013 at 2:25
  • But my input is not a json string Commented May 2, 2013 at 2:27
  • What do you want then? You want the indentation? You want to load json data? For all those, use the builtin json library I wrote above Commented May 2, 2013 at 2:31

2 Answers 2

11

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"]}
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.