JSON

JSON with Python

JSON with Python

This section describes how to encode/decode JSON in Python. For JSON to work with Python, you need to install one of the recommended Python modules.

Python has a built-in package called json, which can be used to work with JSON data. It can be imported in the code as follows :

import json

We can parse a JSON string using the json.loads() method which will convert it to a  Python dictionary. See the following code.

import json
# some valid JSON:
myJson =  '{ "color":"Red", "brand":"Maruti", "name": "WagonR", "type":"Hatchback", "price":400000}'

# parse myJson:
myCar = json.loads(myJson)

# print  Python dictionary myCar
# Iterate over key/value pairs in dict and print them
for key, value in myCar.items():
    print(key, ' : ', value)
This code will give the following output	
color  :  Red
brand  :  Maruti
name  :  WagonR
type  :  Hatchback
price  :  400000

A Python object is converted into a JSON string by json.dumps() method. See the below code:

import json
# a Python object (dict):
myCar = {
"color"  :  "Red",
"brand"  :  "Maruti",
"name"  :  "WagonR",
"type"  :  "Hatchback",
"price"  :  400000
}

# convert into JSON:
myCarJson = json.dumps(myCar)

# the result is a JSON string:
print(myCarJson)

Its output is as follows:
{"color": "Red", "brand": "Maruti", "name": "WagonR", "type": "Hatchback", "price": 400000}