Python Read JSON File and Modify

Python Read JSON File And Modify

One of the most popular formats for storing data is JSON, which is also known as JavaScript Object Notation. The data is stored in key-value pairs, much like the Python dictionary. It has a fast processing rate and is lightweight, straightforward, and quick to code. Working with massive data sets is made simple by it. JavaScript is one of the most popular languages, it has been used throughout the entire area of programming.

Even if you’re not using JavaScript, you’ll frequently need to interact with JSON as a programmer. Since JavaScript is the web’s primary programming language, working with JSON data will be a large part of any app development you perform.

This tutorial will demonstrate how to operate with the JSON data format.

How to create a JSON file

JSON files are the files with the .json extension. JavaScript uses JSON files all the time. Let’s see how we can create a JSON file ourselves. To create a JSON file, first, open up a text editor.

Now that you’ve opened the text editor click on Create a file button in your text editor. Now you can choose any name for the file but just make sure you end the file name with the “.json” extension. So finally, your file name would look something like <filename>.json.

Now just click enter and save the file. There you go, you have a JSON file right there.

The JSON module

json is an in-built Python module that provides a lot of functionalities to help you work with JSON files. You can create, update, load or dump JSON files. It provides APIs similar to standard library modules like marshall and pickles. So it gets easy for users who are familiar with such kind of syntax and interface.

JSON is almost the same as a Python dictionary. So we can create Python dictionaries and then convert them to JSON using the json module.

Related: Learn more about the json module.

json.dumps()

The json.dumps() is one of the most useful methods of the json module. It takes a Python dictionary as input and then returns a string of JavaScript Object Notation which you can later compile in JavaScript. A raw Python dictionary is quite like the JavaScript Object Notation but isn’t completely compatible with JavaScript. Some differences between Python dictionary and JavaScript Object Notation are listed below.

Difference Between JavaScript Object Notation and Python Dictionary

  • Null values in Python are represented by None and in json they’re simply null.
  • Dictionaries can take tuples as values, but JavaScript Object Notation can’t.
  • Python has boolean values with the first letter in uppercase but JavaScript has it all lowercase.

So due to these differences, we need to convert a dictionary into a JavaScript Object Notation compatible format. For this purpose, json.dumps are used. It converts a Python dictionary into JavaScript-compatible JavaScript Object Notation.

import json
dict_ = {'a':1,'b':2,'c':None,'d':False}
jsonified_dict = json.dumps(dict_)
print(dict_)
print(jsonified_dict)
JavaScript Object Notation Dumps
JavaScript Object Notation Dumps

So we just pass the dictionary that we want to jsonify as json.dumps() function and it returns a JavaScript Object Notation encoded format of that dictionary.

json.loads()

json.loads() does the opposite of json.dump(). It simply converts a string of JavaScript Object Notation into a Python dictionary. Let’s see how we can use it.

import json
json_ = '{"a": 1, "b": 2, "c": null, "d": false}'
dict_ = json.loads(json_)
print(json_)
print(dict_)
Json Loads
Json Loads

We just pass a string of JavaScript Object Notation in the json.loads() as the only argument and it returns a dictionary format of that JavaScript Object Notation string.

Related: Learn to pretty print JavaScript Object Notation.

What does json.load() do?

Often programmers get confused between json.load() and json.loads(). They both have the same functionality, except json.loads() is for a JavaScript Object Notation string and json.load() is for a JavaScript Object Notation file. So if you want to read a JavaScript Object Notation file, you would have to use the json.load() function. It lets you read a JavaScript Object Notation file and make changes in it, and then later dump it back in the file.

How to use the json.load() function to read a JavaScript Object Notation file?

First, we’ll create a JavaScript Object Notation file. To create a JavaScript Object Notation file save the file with the .json extension.

A JavaScript Object Notation File
A JavaScript Object Notation File

Now, to read a JavaScript Object Notation file, first, we would have to open the JavaScript Object Notation file as a regular text file. After that, we’ll have to just apply the json.load() function on the file pointer of that file. Let’s see how we can do it in code.

import json
with open('example.json', 'r+') as json_file:
    dict_formatted_data = json.load(json_file)
    print(dict_formatted_data)
Reading A JavaScript Object Notation File
Reading A JavaScript Object Notation File

How to modify JavaScript Object Notation file?

Now that we’ve learned how to read a JavaScript Object Notation file, we can finally move to modify it. In the above example, we saw that the final product that we have now is a dictionary. We know how to convert a dictionary to JavaScript Object Notation. So all thats left now is to modify this dictionary as we want.

We’re going to change the value of 'd' from false to true. To do that, we simply write the following code.

dict_formatted_data['d']=True

This will modify the value of d. Now we can simply use the json.dump() function to dump it back to the same file.

import json
with open('example.json', 'r+') as json_file:
    dict_formatted_data = json.load(json_file)
    dict_formatted_data['d']=True
    json_file.seek(0)
    json.dump(dict_formatted_data,json_file)
JavaScript Object Notation File Modified
JavaScript Object Notation File Modified

There we go. The modification is saved.

Applications of JavaScript Object Notation

JavaScript Object Notation is a universal data encoding format. It is one of the best formats for data interchange and integration between different platforms and languages. It lets you serialize and deserialize data to transmit and receive it between different languages and platforms. It also acts as a configurational file for JavaScript. Due to its popularity in the field of web development, JavaScript is also sometimes referred to as the language of the web. Almost the entire data transmits and receives data in the JavaScript Object Notation format.

Conclusion

Due to its popularity and vast use cases, it’s important to learn how to manipulate JavaScript Object Notation. Its structure is similar to that of the dictionary of Python, and it’s really easy to work with JavaScript Object Notation with Python. JavaScript Object Notation opens the gate for a lot of complex stuff. This is just the beginning of JavaScript Object Notation. Soon you’ll see its use cases every now and then. Make sure you keep practicing cause there’s a lot more to learn.

References

Official Python Documentation.

Stack Overflow thread for the same question.