Welcome! If you want to learn how to work with JSON files in Python, then this article is for you.
Even though JSON files have a specific formatting style, the files themselves contain only regular text data, so you can open a JSON file using Notepad. Notepad runs slowly when opening large files however, so use WordPad for any JSON file over a few hundred kilobytes. How to open.JSON files Get a free file viewer with DownloadFileOpener! This free tool is supported by a comprehensive file viewer database containing detailed information for over 6,000 file extensions in association with over 11,000 unique file type categories. MiTeC JSON Viewer. MiTeC JSON Viewer is a free JSON viewer software, which you can use to. The.json files may contain additional info added in Google Photos, like Description, location etc. More info in this link. When downloading large quantities the.json and.jpg files may be in different packages. Json Editor is a Windows Store app that provides an easy way to open, view, edit and print.json files on all Windows devices! Our goal is to be the best Json viewer and editor App on Windows Store. OS supported include Windows 10 and Windows 8. JSON stands for JavaScript Object Notation.
You will learn:
json
module. loads()
and dumps()
load()
dump()
Are you ready? Let's begin! ✨
The JSON format was originally inspired by the syntax of JavaScript (a programming language used for web development). But since then it has become a language-independent data format and most of the programming languages that we use today can generate and read JSON.
JSON is basically a format used to store or represent data. Its common use cases include web development and configuration files.
Let's see why:
manifest.json
to specify the name of the app, its description, current version, and other properties and settings. Now that you know what the JSON format is used for, let's see its basic structure with an example that represents the data of a pizza order:
These are the main characteristics of the JSON format:
{}
. 💡 Tip: The values that require quotes have to be surrounded by double quotes.
💡 Tip: We typically format JSON with different levels of indentation to make the data easier to read. In this article, you will learn how to add the indentation automatically with Python.
JSON files have specific rules that determine which data types are valid for keys and values.
true
/ false
), null
, or a JSON object.According to the Python Documentation:
Keys in key/value pairs of JSON are always of the type str
. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings.
According to the Google JSON Style Guide:
'orders'
instead of 'order'
if the corresponding value is an array.JSON and Dictionaries might look very similar at first (visually), but they are quite different. Let's see how they are 'connected' and how they complement each other to make Python a powerful tool to work with JSON files.
JSON is a file format used to represent and store data whereas a Python Dictionary is the actual data structure (object) that is kept in memory while a Python program runs.
When we work with JSON files in Python, we can't just read them and use the data in our program directly. This is because the entire file would be represented as a single string and we would not be able to access the key-value pairs individually.
Unless...
We use the key-value pairs of the JSON file to create a Python dictionary that we can use in our program to read the data, use it, and modify it (if needed).
This is the main connection between JSON and Python Dictionaries. JSON is the string representation of the data and dictionaries are the actual data structures in memory that are created when the program runs.
Great. Now that you know more about JSON, let's start diving into the practical aspects of how you can work with JSON in Python.
Luckily for us, Python comes with a built-in module called json
. It is installed automatically when you install Python and it includes functions to help you work with JSON files and strings.
We will use this module in the coming examples.
To use json
in our program, we just need to write an import statement at the top of the file.
Like this:
With this line, you will have access to the functions defined in the module. We will use several of them in the examples.
💡 Tip: If you write this import statement, you will need to use this syntaxto call a function defined in the json
module:
To illustrate how some of the most important functions of the json
module work, we will use a multi-line string with JSON format.
Particularly, we will use this string in the examples. It is just a regular multi-line Python string that follows the JSON format.
data_JSON
.💡 Tip: The Python Style Guide recommends using double quote characters for triple-quoted strings.
We will use the string with JSON format to create a Python dictionary that we can access, work with, and modify.
To do this, we will use the loads()
function of the json
module, passing the string as the argument.
This is the basic syntax:
Here is the code:
Let's focus on this line:
json.loads(data_JSON)
creates a new dictionary with the key-value pairs of the JSON string and it returns this new dictionary.data_dict
.Awesome! If we print this dictionary, we see this output:
The dictionary has been populated with the data of the JSON string. Each key-value pair was added successfully.
Now let's see what happens when we try to access the values of the key-value pairs with the same syntax that we would use to access the values of a regular Python dictionary:
The output is:
Exactly what we expected. Each key can be used to access its corresponding value.
💡 Tip: We can use this dictionary just like any other Python dictionary. For example, we can call dictionary methods, add, update, and remove key-value pairs, and more. We can even use it in a for loop.
When you use loads()
to create a Python dictionary from a JSON string, you will notice that some values will be converted into their corresponding Python values and data types.
This table presented in the Python Documentation for the json
module summarizes the correspondence from JSON data types and values to Python data types and values:
💡 Tip: The same conversion table applies when we work with JSON files.
Now you know how to create a Python dictionary from a string with JSON format.
But sometimes we might need to do exactly the opposite, creating a string with JSON format from an object (for example, a dictionary) to print it, display it, store it, or work with it as a string.
To do that, we can use the dumps
function of the json
module, passing the object as argument:
💡 Tip: This function will return a string.
This is an example where we convert the Python dictionary client
into a string with JSON format and store it in a variable:
Let's focus on this line:
json.dumps(client)
creates and returns a string with all the key-value pairs of the dictionary in JSON format.client_JSON
variable. If we print this string, we see this output:
💡 Tip: Notice that the last value (false
) was changed. In the Python dictionary, this value was False
but in JSON, the equivalent value is false
. This helps us confirm that, indeed, the original dictionary is now represented as a string with JSON format.
If we check the data type of this variable, we see:
So the return value of this function was definitely a string.
A process of type conversion occurs as well when we convert a dictionary into a JSON string. This table from the Python Documentation illustrates the corresponding values:
If we use the dumps
function and we print the string that we got in the previous example, we see:
But this is not very readable, right?
We can improve the readability of the JSON string by adding indentation.
To do this automatically, we just need to pass a second argument to specify the number of spaces that we want to use to indent the JSON string:
💡 Tip: the second argument has to be a non-negative integer (number of spaces) or a string. If indent is a string (such as 't'
), that string is used to indent each level (source).
Now, if we call dumps
with this second argument:
The result of printing client_JSON
is:
That's great, right? Now our string is nicely formatted. This will be very helpful when we start working with files to store the data in a human-readable format.
You can also sort the keys in alphabetical order if you need to. To do this, you just need to write the name of the parameter sort_keys
and pass the value True
:
💡 Tip: The value of sort_keys
is False
by default if you don't pass a value.
For example:
Returns this string with the keys sorted in alphabetical order:
To generate a JSON string that is sorted alphabetically and indented, you just need to pass the two arguments:
In this case, the output is:
💡 Tip: You can pass these arguments in any order (relative to each other), but the object has to be the first argument in the list.
Great. Now you know how to work with JSON strings, so let's see how you can work with JSON files in your Python programs.
Typically, JSON is used to store data in files, so Python gives us the tools we need to read these types of file in our program, work with their data, and write new data.
💡 Tip: a JSON file has a .json
extension:
Let's see how we can work with .json
files in Python.
Let's say that we created an orders.json
file with this data that represents two orders in a pizza shop:
Please take a moment to analyze the structure of this JSON file.
Here are some quick tips:
'orders'
is an array of JSON objects (this array will be represented as list in Python). Each JSON object holds the data of a pizza order. If we want to read this file in Python, we just need to use a with
statement:
💡 Tip: In the syntax above, we can assign any name to file
(green box). This is a variable that we can use within the with
statement to refer to the file object.
The key line of code in this syntax is:
json.load(file)
creates and returns a new Python dictionary with the key-value pairs in the JSON file.data
variable. 💡 Tip: Notice that we are using load()
instead of loads()
. This is a different function in the json
module. You will learn more about their differences at the end of this article.
Once we have the content of the JSON file stored in the data
variable as a dictionary, we can use it to do basically anything we want.
For example, if we write:
The output is 2
because the value of the main key 'orders'
is a list with two elements.
We can also use the keys to access their corresponding values. This is what we typically do when we work with JSON files.
For example, to access the toppings of the first order, we would write:
'orders'
0
).'toppings'
You can see this 'path' graphically in the diagram:
If we print this value, the output is:
Exactly what we expected. You just need to 'dive deeper' into the structure of the dictionary by using the necessary keys and indices. You can use the original JSON file/string as a visual reference. This way, you can access, modify, or delete any value.
💡 Tip: Remember that we are working with the new dictionary. The changes made to this dictionary will not affect the JSON file. To update the content of the file, we need to write to the file.
Let's see how you can write to a JSON file.
The first line of the with
statement is very similar. The only change is that you need to open the file in 'w'
(write) mode to be able to modify the file.
💡 Tip: If the file doesn't exist already in the current working directory (folder), it will be created automatically. By using the 'w'
mode, we will be replacing the entire content of the file if it already exists.
There are two alternative ways to write to a JSON file in the body of the with
statement:
dump
dumps
Let's see them in detail.
First Approach: dump
This is a function that takes two arguments:
Let's say that the pizza shop wants to remove the clients' data from the JSON file and create a new JSON file called orders_new.json
with this new version.
We can do this with this code:
This was the original version of the data in the orders.json
file. Notice that the 'client'
key-value pair exists.
This is the new version in the orders_new.json
file:
If you analyze this carefully, you will see that the 'clients'
key-value pair was removed from all the orders.
However, there is something missing in this file, right?
Please take a moment to think about this... What could it be?
Indentation, of course!
The file doesn't really look like a JSON file, but we can easily fix this by passing the argument indentation=4
to dump()
.
Now the content of the file looks like this:
What a difference! This is exactly what we would expect a JSON file to look like.
Now you know how to read and write to JSON files using load()
and dump()
. Let's see the differences between these functions and the functions that we used to work with JSON strings.
This table summarizes the key differences between these two functions:
💡 Tip: Think of loads()
as 'load string' and that will help you remember which function is used for which purpose.
Here we have a table that summarizes the key differences between these two functions:
💡 Tip: Think of dumps()
as a 'dump string' and that will help you remember which function is used for which purpose.
Finally, there are two important terms that you need to know to work with JSON:
.json
extension.I really hope you liked my article and found it helpful. Now you know how to work with JSON in Python. Follow me on Twitter @EstefaniaCassN and check out my online courses.