How to read, write and Parse JSON to a file in Python

How to read, write and Parse JSON to a file in Python

While learning Python, you must have learned about file handling. It is a way of storing data in the form of text, binary, or even CSV. The main aim is to store data. While binary files cannot be read by humans, text and CSV files can. Another way of storing data in a human-readable format is the JSON format.

Introduction

The JSON format is a text-based open standard used for data interchange. It was originally designed by the ECMAScript language committee, which serves as an alternative to XML or HTML in describing data structures. It also has its own advantages, such as better readability and faster parsing speed than XML. In our article today, we will talk in detail about JSON files, their syntax, and how to read and write through them. Without wasting any time, let’s jump right into the article.

What is JSON file?

It was created by Douglas Crockford while working at Yahoo! in 2007. The syntax uses two spaces instead of one space between each value (like many other text formats). In addition to being human-readable and machine-processable, it’s also language-independent, meaning you can use it interchangeably with any programming language that supports string literals, such as Python!

Import JSON Module

You can import JSON by using the following code:

import json
Code language: Python (python)

JSON Syntax

JSON syntax uses curly braces and periods to delimit values from each other. It usually ignores the White space when parsing JSON strings; however, it does not allow any whitespace between elements or attributes within an object or array unless it’s part of the value itself.

Python JSON parser

The Python module has many useful functions for working with JSON data. The simplest way to read a file is by using the standard library module called “JSON.” This module in Python has its own in-built decoder and encoder for JSON data. If you want to parse this data, the module provides two methods, namely json.load() and json.loads().

Example: Converting Python JSON to dictionary data

In this section, we will discuss two examples where we can convert JSON data into dictionary data. For the first example, we will store the dictionary data in a string, load it into a variable, and print the dictionary using JSON functions.

import json json_strobj = '{"ID": 102, "emp_name": "Suraj", "Salary": 40000 }' py_json_dict = json.loads(json_strobj) print(py_json_dict )
Code language: Python (python)

Continue reading the article to learn about the second method, which involves reading the JSON file data into dictionary data and printing it by loading the file components into a variable using JSON functions.

Python Convert to JSON string

Import the json module and call dump() or load(). This will produce a new object with all of your original data available as attributes. The returned value is also a Python dictionary, so you can treat it like any other Python dictionary.

Example: Convert a dict to JSON

The data Structures are represented by a dictionary, where keys are strings and values can be any other object. A simple example given below converts this dictionary into a string using a JSON function called json.dump().

import json pyjs_dict = { "ID": 156, "emp_age": 23, "emp_name": "Lakshya" } json_strobj = json.dumps(pyjs_dict) print(json_strobj)
Code language: Python (python)

Read JSON file Python

In this section, just like we can read data from binary files using the Pickle module’s load function, JSON also offers the same function, which can load the JSON file data into a variable, and we can print it to display it.

Python: Reading JSON from files with json.load() and json.loads ()

As promised, here is the second method using the json.load() function to read the JSON file, load its elements into a variable, and print them.

import json #suppose there is a dictionary present in the JS_Data file with open("JS_data.json", "r") as json_file: data_dict = json.load(json_file) print(data_dict)
Code language: Python (python)

As discussed in the first code example, if you want to parse a string into a JSON data object, you use the json.loads() function.

import json json_strobj = '{"ID": 102, "emp_name": "Suraj", "Salary": 40000 }' py_json_dict = json.loads(json_strobj) print(py_json_dict )
Code language: Python (python)

Writing JSON content to a file

In this section, just like we can write data into binary files using the Pickle module’s dump function, JSON also offers the same function, which can dump and store the data into a JSON file.

Writing JSON to a File with Python with json.dump() and json.dumps()

The json.dump function involves inputting content from the user and dumping or writing it into a JSON file-like object. You can refer to the example given below for a better understanding.

import json pyjs_dict = { "ID": 187, "name": "Kartik, "marks": 98 } with open("samp_dump_file.json", "w") as file_w: json.dump(pyjs_dict, file_w)
Code language: Python (python)

For json.dumps(), the main difference from the above function is that it parses the data into a string object rather than a file object. The example for the same has already been covered in the article, but you can still refer to the example given below for your ease.

import json pyjs_dict = { "name": "Priyanka", "age": 23, "city": "Bangalore" } json_strobj = json.dumps(pyjs_dict) print(json_strobj)
Code language: Python (python)

JSON pretty print in Python

JSON pretty print is nothing but a way to represent the data in an organized manner by adding the indent parameter to it.

For example: Python pretty print JSON can be done as following:

import json pyjs_dict = { "sport_item": "Basketball", "qty": 478, "area": "rajeshnagar" } json_strobj = json.dumps(pyjs_dict, indent=4) print(json_strobj)
Code language: Python (python)

Conclusion

It’s time we conclude our article today. We discussed the JSON module in Python, discussed its syntax, and covered the ways to read the dictionary and string data using the json.load() and json.loads() functions available in the module. We also talked about how to write dictionary data into JSON file objects and string objects using the json.dump() and json.dumps() functions. At last, we have taken an example to show how to pretty print JSON data using the indent parameter.

I hope my article is helpful. I will be grateful if you could share this article with your friends. Queries are always welcome in the comment section. We will be back soon with another fantastic article. Till then, keep coding.

Frequently Asked Questions to Resolve (FAQs)

How do I read, write and Parse a JSON file in Python?

The main theme of the article revolves around the same. To read, write, and parse a JSON file in simple terms, we must first import the built-in library json. Now to read and write dictionary data, we can use the json.load() and json.dump() functions. For parsing JSON files into string objects, you can use the json.load() function, and if you want to write into a JSON file object, use json.dumps().

Can Python read, write, and parse JSON files?

Yes, all of these operations are possible in Python thanks to the built-in JSON library. 

Does Python parse, read, and write JSON?

Yes, Python is perfectly capable of parsing, reading, and writing JSON. The library is specially designed to cater to these needs.

How does Python handle parsing, reading, and writing JSON?

The json library in Python is very straightforward and easy to use. Hence, it is a breeze to handle JSON data in Python with the help of functions such as json.load(),json.loads(),json.dump(), and json.dumps().

What are the ways Python parses, reads, and writes JSON?

Python offers several ways to parse, read, and write JSON, but the most commonly used method is using the built-in json library. With this, you can read JSON data from a file or from a string, parse this data into a dictionary, modify the data within the dictionary, and then write the dictionary back to a JSON file.

Sharing is caring

Did you like what Pravin Gupta wrote? Thank them for their work by sharing it on social media.