In this article, we are going to see how to read JSON file in Python. JSON (JavaScript Object Notation) is an easy to read syntax for storing and exchanging the data. Its a very commonly used structured data format over the applications.

How to read JSON file in Python?

Reading a JSON file in python is as easy as reading a text file in python.  Python has an in-built JSON package called json, which can be used to work with json string/files.

Now lets read a simple below JSON string; it contains simple string values with an array of languages known.

{
  "id": "1015",
  "name": "CHANDRA SHEKHAR",
  "surname": "GOKA",
  "languages_known": ["English","Telugu"]
}

Reading JSON String in Python:

import json

def read_josn(str):
    json_obj = json.loads(str)
    print("complete JSON : ", json_obj)
    print(json_obj['name'])
    print(json_obj['languages_known'])

if __name__ == '__main__':
    str = """
    {
          "id": "1015",
          "name": "CHANDRA SHEKHAR",
          "surname": "GOKA",
          "languages_known": ["English","Telugu"]
    }
    """
    read_josn(str)

json.loads() is a method used to de-serialize the json string document into python object.

Read JSON File in Python:

import json

def read_josn_file(path):
    with open(path) as file:
        json_obj = json.load(file)
        print("complete JSON File : ", json_obj)
        print(json_obj['name'])
        print(json_obj['languages_known'])

if __name__ == '__main__':
    path ="sample.json"
    read_josn_file(path)

json.load() is a method used to de-serialize the file object containing json document into python object. Once we get the Python object we can freely read the data like reading/looping data from python dictionary.

Output:

complete JSON File :  {'id': '1015', 'name': 'CHANDRA SHEKHAR', 'surname': 'GOKA', 'languages_known': ['English', 'Telugu']}
CHANDRA SHEKHAR
['English', 'Telugu']

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment