JSON Python Example

Python is a scripting language that is used by Google, Facebook, Youtube, and others. Python enables a programmer to build web applications, desktop applications, mobile apps, and what you can imagine, possibilities are endless. Python has json module using which you can handle JSON data. There are two functions in json module that are important for us-

  • json.loads()- This function decodes JSON data into Python dictionary.
  • json.dumps()- This function encodes Python dictionary into JSON data.

How to convert JSON data into Python dictionary

requests module is used to fetch data from the internet. Run the below command to this module-

pip install requests

Let's understand the entire process with the help of below example-

import requests
import json

json_string = requests.get('http://www.tutorialsandyou.com/json/product.json').text
arr = json.loads(json_string)
print("Name: "+arr['name'])
print("Description: "+arr['description'])
print("Price: "+str(arr['price']))
print("Sizes: "+str(arr['sizes'][0])+", "+str(arr['sizes'][1]))

Output

Name: Reebok Athletic Shoes
Description: A pair of shoes that are designed for athletic championships
Price: 2000
Sizes: 6, 7

How to convert Python dictionary into JSON data

json.dumps() function will transform the data present in Python dictionary into JSON string.

import json

dict = {'name':'Samsung Galaxy J7', 'price':15500, 'color':["black","grey"], 'inStock':True}
json_string = json.dumps(dict)
print(json_string)

Output

{"color": ["black", "grey"], "price": 15500, "name": "Samsung Galaxy J7", "inStock": true}