Python read json file to dictionary

Introduction

In this code snippet, we are going to demonstrate how to read JSON data from file into a Python dictionary data structure.

String to JSON

The function json.loads() can be used to load JSON data from string to dictionary. To load the data from file, we need to convert the file to string. Let us take an example...

Example JSON file

Assume we have the following json file test.json

{  
    "cars": [  
       {  
          "id":"01",  
          "model": "Honda",  
          "color": "White"  
       },  
       {  
          "id":"02",  
          "model": "Ford",  
          "color": "Black"  
       }  
    ]  
 } 

Here is the Python code to load the JSON file above...

# Import the json module
import json

# Open a json file into a json object
# Note that F.read() returns the content
# of the file as a string so we should call
# json.loads()
with open('test.json', encoding='utf-8') as F:
    json_data = json.loads(F.read())

# Print loaded json object
print(json_data)
print(type(json_data))

# We can load the file directly without 
# reading it as a string as follows
with open('test.json') as F:
    json_data = json.load(F)
   
# Print loaded json object
print(json_data)
print(type(json_data))

If you run the code snippet above, you should get the following output (using Python 2.x)...

{u'cars': [{u'color': u'White', u'model': u'Honda', u'id': u'01'}, {u'color': u'Black', u'model': u'Ford', u'id': u'02'}]}
<type 'dict'>
{u'cars': [{u'color': u'White', u'model': u'Honda', u'id': u'01'}, {u'color': u'Black', u'model': u'Ford', u'id': u'02'}]}
<type 'dict'>

We can also load the file without specifying a file handle. Take a look…

Loading the file in one shot

# Import the json module
import json

# Load the file 
json_data = json.loads(open('test.json').read())

# Print loaded json object
print(json_data)
print(type(json_data))

Thanks for reading. Questions ? please use the comments section below.

Tags:,

Leave a Reply