Python : Reading JSON file

Python3 provides

  • an in-built json package for working with JSON ( JavaScript Object Notation ) data.
Module Function Usage
json json.load() returns json data in a dictionary format

Consider the below JSON file : stream.json

{
    "Customer": "Deltoid",
    "Subscription" : "Monthly",

    "Video stream": {

        "Netflix" : {
            "Monthly price" : "£10",
            "Movies" : ["The Guilty", "Run", "Intrusion"],
            "Series" : ["Bread Story", "Ninjago", "Glitter Force"]
        },

        "Amazon Prime": {
            "Monthly price" : "£8",
            "Movies" : ["Joker", "Infinite", "Rocket Singh"],
            "Series" : ["Peppa Pig", "Fireman Sam", "Bing"]
        },

        "Disney" : {
            "Monthly price" : "£12",
            "Movies" : ["Luca", "The Lion King", "Star Wars"],
            "Series" : ["Mickey Mouse", "Pink Panther"]
        }
    }
}

Python3 : Program for reading a JSON file.

import json

def main() :

    with open ('stream.json') as f :

        try :

            data = json.load(f)

            if "Customer" in data :
                print ("Customer name : " + data["Customer"])

            if "Subscription" in data :
                print ("Subscription duration : " + data["Subscription"])

            for key, value in data["Video stream"].items() :

                stream = key
                stream_data = value

                print("\nStream : " + stream)

                if "Monthly price" in stream_data :
                    print("Monthly price : " + stream_data["Monthly price"])

                if "Movies" in stream_data :
                    movie_list = stream_data["Movies"]
                    cnt = 1
                    print("----- Movies -----")
                    for movie in movie_list :
                        print (str(cnt) + " . " + movie)
                        cnt += 1

                if "Series" in stream_data :
                    movie_list = stream_data["Series"]
                    cnt = 1
                    print("----- Series -----")
                    for movie in movie_list :
                        print (str(cnt) + " . " + movie)
                        cnt += 1

        except OSError as err:
            print("OS error: {0}".format(err))

if __name__ == "__main__" :
    main()

Output

Customer name : Deltoid
Subscription duration : Monthly

Stream : Netflix
Monthly price : £10
----- Movies -----
1 . The Guilty
2 . Run
3 . Intrusion
----- Series -----
1 . Bread Story
2 . Ninjago
3 . Glitter Force

Stream : Amazon Prime
Monthly price : £8
----- Movies -----
1 . Joker
2 . Infinite
3 . Rocket Singh
----- Series -----
1 . Peppa Pig
2 . Fireman Sam
3 . Bing

Stream : Disney
Monthly price : £12
----- Movies -----
1 . Luca
2 . The Lion King
3 . Star Wars
----- Series -----
1 . Mickey Mouse
2 . Pink Panther


Copyright (c) 2019-2021, Algotree.org.
All rights reserved.