Python Classroom Series – 09/Sept/2021

JSON

  • This is very popular data interchange format
  • JSON (Java Script Object Notation)
  • JSON is collection of name and value pairs
"name": <value>
  • Value can be number/text/boolean which are considered as simple data
"course": "Python" //text
"duration": 90 //number
"isonline": true //boolean
  • Value can be list/array
"courses": [ "Python", "Django", "DataScience" ]
  • Value can be complex and might require some more name value pairs
"address": {
    "building": "nilgiri block",
    "street": "ameerpet main road",
    "landmark": "ameerpet metro",
    "city": "Hyderabad",
    "state": "Telangana"
}
  • Lets try to write a json which describes data of menu of hotel. Every json generally starts with {} and the file will be saved with .json extension
{
    "name": "Bluefox",
    "menu": {
        "breakfast": {
            "hours": "6-11",
            "items": ["idly", "vada", "dosa" ]
        },
        "lunch": {
            "hours": "11:30-3:00",
            "items": [
                "south indian combo",
                "north indian combo",
                "Biryani"
                ]
        }
    }

}
  • Refer Here for the python standard library json
  • Sample python code to read a json file
import json
with open('menu.json', mode='rt') as f:
    menu = json.load(f) # json file is loaded into menu as dict
    print(menu['menu']['breakfast']['items'])

  • Lets write a sample python application to write the json file
import json


def store_product(name, price):
    with open('products.json', mode='wt') as file:
        product_dict = dict()
        product_dict['name'] = name
        product_dict['price'] = price
        json.dump(product_dict, file,indent=4)


store_product('iphone', 120000)

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin