Signup/Sign In

How to read JSON file in Python

In this article, we will learn various ways to read JSON files in Python. We will use some built-in functions available in Python for JSON and some related custom examples as well. We will compare text each function with examples in this module. Let's first have a quick look over the full form of JSON, an introduction to JSON, and how JSON files are used. Look at the following examples showing different parsing functions to read JSON documents in Python.

What is JSON?

JSON stands for JavaScript Object Notation. It is a popular data format used for representing structured data. It is a lightweight format that is used for data interchanging. The data representation in JSON is similar to that of Python Dictionary. It is a collection of name/value pairs. In JSON, it is common to transmit and receive data between a server and web application in JSON format. It is also common to store a JSON object in a file. JSON data can be in the form of the object, array, value, string, or number.

In Python, JSON exists as a string or more like a dictionary having key-value pairs where keys must be a string and values can be of any type say object, array, value, string, or a number.

JSON Example

data = '{"model number": "RX234", "customers": ["Adam", "Paul"], “price”: 45000, “quantity”: 12, “company”: “Samsung”}'

For reading any JSON file and to work with JSON (string, or file containing JSON object) you must import JSON module in python script.

Reading JSON file in Python

Reading JSON files in Python language is quite easy. We just need to import JSON module in the file and use its methods. Reading of JSON data is carried out using either of the following functions.

  1. json.load()

  2. json.loads()

  3. json.dumps()

1. Reading JSON Using json.load() Function

Python provides json.load() method to read a file containing the JSON object. Reading JSON data from a file is quite an easy task in python as python script provides a built-in JSON module and JSON has a built-in load() function to carry out the parsing process. Using the same JSON module, we can extract and parse the JSON string directly from a file object. This method is used when the programmer already has a JSON file with structured data.

Syntax

json.load(file object)

Sample JSON File

This JSON file, we will read with the python script.

{"model number": "RX234",
 "customers": ["Adam", "Paul"],
 "price": 45000,
 “quantity”: 12,
 “company”: “Samsung”
}

Example

In the following example, we are going to read a JSON file and then print out the data. This json.load() function reads the string from the JSON file. The json.load(file) function creates and returns a new Python dictionary with the key-value pairs in the JSON file. Then, this dictionary is assigned to the data variable, and the result is displayed.

import json

with open('path_to_file/model.json') as f:
     data = json.load(f)

print(data)


{"model number": "RX234", "customers": ["Adam", "Paul"], “price”: 45000, “quantity”: 12, “company”: “Samsung”}

In the above code to read the JSON file, first, we have imported the JSON module and then we have used the open() function to read the JSON file bypassing the JSON file path along with the name of the file as an argument. Then, the file is parsed using json.load() method which gives us a dictionary and the result is stored in the data variable. As shown in the output, the JSON string is printed in the form of key-value pairs.

2. Reading JSON Using json.loads() Function

If you have a JSON string rather than a JSON file then you can parse it by using the json.loads() method. The json.loads() method does not take the file path, but the file contents as a string, using the fileobject.read(). With json.loads() function, we can return the content of the file. This function is useful to the programmer when he has a JSON string.

Syntax

json.loads(jsonstring) #for Json string

json.loads(fileobject.read()) #for fileobject

EXAMPLE

The given example will show how to read a JSON string, as well as a file object by using JSON module in Python.

import json 
  
# JSON string 
a =  '{"name": "Flora", "age": 16, "place": "london"}'

# deserializes into dict and returns dict. 
y = json.loads(a) 
  
print("JSON string = ", y) 
print() 
  
  
  
# JSON file 
f = open ('model.json', "r") 
  
# Reading from file 
data = json.loads(f.read()) 
  
print(data)


JSON string = {"name": "Flora", "age": 16, “place”: "london"}'
{"model number": "RX234", "customers": ["Adam", "Paul"], “price”: 45000, “quantity”: 12, “company”: “Samsung”}

3. Reading JSON Using json.dumps() Function

This is quite the same as json.load() but with additional parameters and functionality. The json.dumps() makes the original JSON output a human-readable output form with proper indentation. This process of presenting JSON data into a human-readable format with proper indentation and spacing is known as Pretty Printing. Pretty Printing is done by easily passing an integer value to the indent parameter.

Syntax

json.dumps(JSON string, indent parameter)

Example

Here, we used the dumps() function to read JSON string in human-readable form.

import json

#define JSON string
data = {'model':[{'number': 'RX341', 'price': 35000, 'qty': 12, 'company': 'Samsung'}]}

#use dumps() with two parameters and store resultant in result variable
result= json.dumps(data, indent=4)

print(result)


{
"model": [
{
"number": "RX341",
"price": "35000",
"qty": "12",
"company": "Samsung"
}
]
}

As you can see in the above output, the indent parameter is set to 4. This is actually quite useful since you'll often have to read JSON data during development.

In the given figure, you can see json.loads() converts a string to JSON object while json.dumps() converts JSON object to string.

Conclusion

In this article, we learned about JSON files and how we use JSON strings and file objects. We learned different ways to read JSON file by three built-in JSON functions - json.load(), json.loads() and json.dumps(). We also used the fileobject.read() function to read file object. We saw differences between the functions. We used some custom parsing codes as well to parse the JSON file using different JSON files.



About the author:
An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection.