How to generate JSON output using Python?

PythonJSONProgramming

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
   }
}
raja
Published on 20-Apr-2018 07:16:15
Advertisements