How to generate JSON output using Python?



The json module in python allows you to dump a dict to json format directly. To use it,

Example

import json

my_dict = {
   'foo': 42,
   'bar': {
      'baz': "Hello",
      'poo': 124.2
   }
}
my_json = json.dumps(my_dict)
print(my_json)

Output

This will give the output −

'{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'

You can also pass indent argument to prettyprint the json. 

example

import json

my_dict = {
   'foo': 42,
   'bar': {
      'baz': "Hello",
      'poo': 124.2
   }
}
my_json = json.dumps(my_dict, indent=2)
print(my_json)

Output

This will give the output −

{
   "foo": 42,
   "bar":
   {
      "baz": "Hello",
      "poo": 124.2
   }
}
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements