JSON is compatible with most programming languages and can easily be integrated as they have built-in functionalities to read, write and parse JSON. JSON is commonly used across the computing world for APIs and for Config files of different programs such as games. It is also used to transfer data from a server to the client and vice versa. In this post, we will go through a guide on how to read, write and parse JSON in python. Python has a built-in package named JSON which can be used to manipulate JSON data.

How to Convert JSON to Python Dictionary (Parse JSON)

We can use the json.loads() method to parse JSON into a Python dictionary. We have to provide the JSON in string format to the json.loads() function because this function takes the string and converts the string into a Python dictionary. In the example given below, the employee is a JSON string while the employee-dict is a python dictionary.

Output

How to Convert a Python Dictionary to a JSON String

In the previous section, we learned how to convert a JSON string to a Python dictionary. Now we will do the opposite and convert the Python dictionary into a JSON string.

Output

How to Read a JSON File

We can use the json.load() method to read a JSON object, in Python. First, created a data.json file with following content: Then run the below program to data from JSON file and print on the screen.

Output

How to Write JSON to a File using Python

We can use the json.dump() method to write JSON to a .json file. The program given below creates a new file named employee.json. If the file already exists then it only opens the file in ‘w’ mode. The ‘w’ mode means that the file is opened in write mode. Then json.dump() converts the python dictionary “employee_dict” into a JSON string and writes it into the json file.

Output:

Conclusion

JSON has become the most common method to store and transfer data in recent times. Its ease of use has made it wildly popular among developers. In this write-up we have learned json.loads(), json.dumps(), json.load(), and json.dump() methods. These methods help us manipulate, read, write and parse JSON in python.

How to Read  Write   Parse JSON in Python   TecAdmin - 31How to Read  Write   Parse JSON in Python   TecAdmin - 37How to Read  Write   Parse JSON in Python   TecAdmin - 59How to Read  Write   Parse JSON in Python   TecAdmin - 37