Read Json Object and Save It in a Table Python

Welcome! If y'all desire to acquire how to work with JSON files in Python, and so this article is for yous.
Yous volition learn:
- Why the JSON format is so of import.
- Its basic construction and data types.
- How JSON and Python Dictionaries piece of work together in Python.
- How to work with the Python built-in
json
module. - How to convert JSON strings to Python objects and vice versa.
- How to use
loads()
anddumps()
- How to indent JSON strings automatically.
- How to read JSON files in Python using
load()
- How to write to JSON files in Python using
dump()
- And more!
Are you ready? Permit'due south begin! ✨
🔹 Introduction: What is JSON?

The JSON format was originally inspired past the syntax of JavaScript (a programming language used for spider web evolution). But since and so it has become a linguistic communication-independent data format and almost of the programming languages that nosotros utilize today can generate and read JSON.
Importance and Use Cases of JSON
JSON is basically a format used to store or represent information. Its common use cases include web development and configuration files.
Let's see why:
- Web Development: JSON is commonly used to send data from the server to the customer and vice versa in web applications.

- Configuration files: JSON is likewise used to store configurations and settings. For example, to create a Google Chrome App, you need to include a JSON file called
manifest.json
to specify the proper noun of the app, its description, electric current version, and other properties and settings.

🔸 JSON Structure and Format
Now that y'all know what the JSON format is used for, let'due south meet its basic structure with an case that represents the data of a pizza guild:
{ "size": "medium", "price": xv.67, "toppings": ["mushrooms", "pepperoni", "basil"], "extra_cheese": imitation, "commitment": true, "client": { "name": "Jane Doe", "phone": nada, "email": "janedoe@email.com" } }
These are the master characteristics of the JSON format:
- There is a sequence of key-value pairs surrounded by curly brackets
{}
. - Each key is mapped to a particular value using this format:
"key": <value>
💡 Tip: The values that require quotes take to be surrounded by double quotes.
- Primal-value pairs are separated past a comma. Just the last pair is not followed by a comma.
{ "size": "medium", # Comma! "price": 15.67 }
💡 Tip: Nosotros typically format JSON with different levels of indentation to make the information easier to read. In this article, yous volition learn how to add together the indentation automatically with Python.
JSON Information Types: Keys and Values
JSON files have specific rules that decide which data types are valid for keys and values.
- Keys must exist strings.
- Values tin exist either a string, a number, an array, a boolean value (
true
/imitation
),aught
, or a JSON object.
According to the Python Documentation:
Keys in key/value pairs of JSON are always of the blazon str
. When a lexicon is converted into JSON, all the keys of the lexicon are coerced to strings.
Style Guide
Co-ordinate to the Google JSON Fashion Guide:
- E'er choose meaningful names.
- Array types should accept plural key names. All other key names should be singular. For case: utilize
"orders"
instead of"club"
if the corresponding value is an array. - There should be no comments in JSON objects.
🔹 JSON vs. Python Dictionaries
JSON and Dictionaries might look very similar at first (visually), but they are quite different. Let'due south 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 information whereas a Python Dictionary is the actual data structure (object) that is kept in retentivity while a Python plan runs.
How JSON and Python Dictionaries Work Together

When we piece of work with JSON files in Python, we can't just read them and use the information in our plan directly. This is considering the entire file would be represented as a single string and we would not be able to access the fundamental-value pairs individually.
Unless...
We use the key-value pairs of the JSON file to create a Python lexicon that nosotros tin 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 cord representation of the data and dictionaries are the actual data structures in memory that are created when the program runs.
Neat. Now that yous know more most JSON, allow's kickoff diving into the practical aspects of how yous tin can work with JSON in Python.
🔸 The JSON Module
Luckily for u.s., Python comes with a built-in module called json
. It is installed automatically when y'all install Python and information technology includes functions to help you work with JSON files and strings.
We will use this module in the coming examples.
How to Import the JSON Module
To use json
in our program, nosotros just demand to write an import statement at the top of the file.
Like this:

With this line, you lot will have access to the functions divers in the module. We volition use several of them in the examples.
💡 Tip: If you lot write this import statement, y'all will need to utilize this syntax to call a part defined in the json
module:

🔹 Python and JSON Strings
To illustrate how some of the almost important functions of the json
module work, we will use a multi-line string with JSON format.
JSON Cord
Specially, we will use this cord in the examples. Information technology is just a regular multi-line Python string that follows the JSON format.
data_JSON = """ { "size": "Medium", "price": 15.67, "toppings": ["Mushrooms", "Extra Cheese", "Pepperoni", "Basil"], "client": { "proper noun": "Jane Doe", "telephone": "455-344-234", "email": "janedoe@email.com" } } """
- To define a multi-line cord in Python, nosotros use triple quotes.
- And then, we assign the string to the variable
data_JSON
.
💡 Tip: The Python Style Guide recommends using double quote characters for triple-quoted strings.
JSON Cord to Python Dictionary
We will use the string with JSON format to create a Python lexicon that nosotros can admission, piece of work with, and modify.
To practice this, we will use the loads()
office of the json
module, passing the string equally the argument.
This is the basic syntax:

Here is the code:
# Import the module import json # String with JSON format data_JSON = """ { "size": "Medium", "price": 15.67, "toppings": ["Mushrooms", "Extra Cheese", "Pepperoni", "Basil"], "client": { "proper noun": "Jane Doe", "phone": "455-344-234", "email": "janedoe@email.com" } } """ # Convert JSON string to dictionary data_dict = json.loads(data_JSON)
Let's focus on this line:
data_dict = json.loads(data_JSON)
-
json.loads(data_JSON)
creates a new dictionary with the key-value pairs of the JSON string and it returns this new lexicon. - Then, the lexicon returned is assigned to the variable
data_dict
.
Awesome! If we impress this lexicon, nosotros encounter this output:
{'size': 'Medium', 'price': 15.67, 'toppings': ['Mushrooms', 'Extra Cheese', 'Pepperoni', 'Basil'], 'client': {'name': 'Jane Doe', 'phone': '455-344-234', 'electronic mail': 'janedoe@electronic mail.com'}}
The dictionary has been populated with the data of the JSON string. Each key-value pair was added successfully.
Now allow's come across what happens when we attempt to access the values of the key-value pairs with the same syntax that nosotros would use to access the values of a regular Python dictionary:
print(data_dict["size"]) print(data_dict["cost"]) print(data_dict["toppings"]) print(data_dict["client"])
The output is:
Medium 15.67 ['Mushrooms', 'Extra Cheese', 'Pepperoni', 'Basil'] {'proper name': 'Jane Doe', 'phone': '455-344-234', 'email': 'janedoe@email.com'}
Exactly what we expected. Each key tin can be used to access its corresponding value.
💡 Tip: We can use this lexicon just like any other Python dictionary. For instance, we tin call dictionary methods, add, update, and remove key-value pairs, and more. We can even use it in a for loop.
JSON to Python: Type Conversion
When you utilise loads()
to create a Python dictionary from a JSON string, you will notice that some values volition exist 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 information types and values:

💡 Tip: The aforementioned conversion table applies when nosotros work with JSON files.
Python Dictionary to JSON String
At present you know how to create a Python dictionary from a string with JSON format.
But sometimes nosotros might need to exercise exactly the reverse, creating a string with JSON format from an object (for example, a dictionary) to impress it, display it, store it, or piece of work with it as a string.
To exercise that, we can use the dumps
office of the json
module, passing the object every bit argument:

💡 Tip: This part 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:
# Python Dictionary customer = { "proper noun": "Nora", "age": 56, "id": "45355", "eye_color": "green", "wears_glasses": Fake } # Get a JSON formatted string client_JSON = json.dumps(client)
Let's focus on this line:
client_JSON = json.dumps(customer)
-
json.dumps(client)
creates and returns a string with all the key-value pairs of the dictionary in JSON format. - And so, this string is assigned to the
client_JSON
variable.
If we impress this cord, nosotros see this output:
{"name": "Nora", "age": 56, "id": "45355", "eye_color": "green", "wears_glasses": false}
💡 Tip: Find that the concluding value (false
) was changed. In the Python dictionary, this value was False
merely in JSON, the equivalent value is fake
. This helps the states 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:
<class 'str'>
So the return value of this office was definitely a string.
Python to JSON: Blazon Conversion
A process of type conversion occurs as well when nosotros convert a dictionary into a JSON string. This table from the Python Documentation illustrates the respective values:

How to Print JSON With Indentation
If nosotros use the dumps
function and nosotros print the string that we got in the previous example, nosotros see:
{"name": "Nora", "historic period": 56, "id": "45355", "eye_color": "greenish", "wears_glasses": imitation}
But this is not very readable, right?
We can improve the readability of the JSON string by calculation indentation.
To exercise this automatically, we just need to pass a second statement 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 2nd statement:
client_JSON = json.dumps(client, indent=4)
The outcome of press client_JSON
is:
{ "name": "Nora", "age": 56, "id": "45355", "eye_color": "green", "wears_glasses": imitation }
That's peachy, right? At present our string is nicely formatted. This will be very helpful when we start working with files to shop the data in a man-readable format.
How to Sort the Keys
You can likewise sort the keys in alphabetical gild if you lot need to. To do this, you simply demand to write the proper noun 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 instance:
client_JSON = json.dumps(client, sort_keys=Truthful)
Returns this string with the keys sorted in alphabetical order:
{"age": 56, "eye_color": "green", "id": "45355", "name": "Nora", "wears_glasses": false}
How to Sort Alphabetically and Indent (at the aforementioned fourth dimension)
To generate a JSON string that is sorted alphabetically and indented, you lot just demand to pass the two arguments:

In this case, the output is:
{ "historic period": 56, "eye_color": "green", "id": "45355", "proper noun": "Nora", "wears_glasses": faux }
💡 Tip: You can pass these arguments in any order (relative to each other), but the object has to exist the start argument in the list.
Slap-up. Now you know how to work with JSON strings, then let's run across how you lot can piece of work with JSON files in your Python programs.
🔸 JSON and Files
Typically, JSON is used to store data in files, and so Python gives us the tools we need to read these types of file in our program, work with their data, and write new information.
💡 Tip: a JSON file has a .json
extension:

Let's see how we can piece of work with .json
files in Python.
How to Read a JSON File in Python
Let'south say that we created an orders.json
file with this data that represents 2 orders in a pizza store:
{ "orders": [ { "size": "medium", "price": 15.67, "toppings": ["mushrooms", "pepperoni", "basil"], "extra_cheese": simulated, "commitment": truthful, "client": { "name": "Jane Doe", "telephone": zippo, "email": "janedoe@e-mail.com" } }, { "size": "minor", "price": half-dozen.54, "toppings": null, "extra_cheese": truthful, "delivery": false, "client": { "name": "Foo Jones", "telephone": "556-342-452", "email": null } } ] }
Please take a moment to analyze the construction of this JSON file.
Here are some quick tips:
- Notice the data types of the values, the indentation, and the overall construction of the file.
- The value of the primary key
"orders"
is an array of JSON objects (this array will be represented as listing in Python). Each JSON object holds the information of a pizza club.
If we desire to read this file in Python, we just demand to apply a with
statement:

💡 Tip: In the syntax in a higher place, we can assign any name to file
(green box). This is a variable that we tin use within the with
argument to refer to the file object.
The key line of code in this syntax is:
data = json.load(file)
-
json.load(file)
creates and returns a new Python dictionary with the key-value pairs in the JSON file. - And so, this dictionary is assigned to the
data
variable.
💡 Tip: Discover that nosotros are using load()
instead of loads()
. This is a dissimilar office 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 equally a dictionary, we can use it to exercise basically anything we want.
Examples
For example, if we write:
print(len(data["orders"]))
The output is 2
because the value of the main cardinal "orders"
is a list with two elements.
We can likewise use the keys to access their corresponding values. This is what we typically practise when nosotros piece of work with JSON files.
For example, to access the toppings of the offset order, we would write:
information["orders"][0]["toppings"]
- Start, nosotros select the main key
"orders"
- Then, we select the get-go element in the list (index
0
). - Finally, we select the value that corresponds to the key
"toppings"
You tin can meet this "path" graphically in the diagram:

If we impress this value, the output is:
['mushrooms', 'pepperoni', 'basil']
Exactly what we expected. You only demand to "dive deeper" into the construction of the dictionary by using the necessary keys and indices. You can use the original JSON file/string as a visual reference. This style, you tin can access, modify, or delete any value.
💡 Tip: Call up that we are working with the new dictionary. The changes made to this dictionary will not impact the JSON file. To update the content of the file, we need to write to the file.
How to Write to a JSON File
Allow'due south come across how you can write to a JSON file.
The first line of the with
statement is very like. The only change is that you demand to open the file in 'west'
(write) mode to be able to modify the file.

💡 Tip: If the file doesn't be already in the electric current working directory (folder), it will be created automatically. Past using the 'west'
way, we will exist 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
Allow'southward encounter them in detail.
Offset Approach: dump
This is a office that takes two arguments:
- The object that will be stored in JSON format (for case, a dictionary).
- The file where information technology will be stored (a file object).

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 lawmaking:
# Open the orders.json file with open("orders.json") as file: # Load its content and make a new lexicon data = json.load(file) # Delete the "client" central-value pair from each club for order in data["orders"]: del order["client"] # Open (or create) an orders_new.json file # and store the new version of the data. with open("orders_new.json", 'w') equally file: json.dump(data, file)
This was the original version of the data in the orders.json
file. Notice that the "client"
key-value pair exists.
{ "orders": [ { "size": "medium", "cost": 15.67, "toppings": ["mushrooms", "pepperoni", "basil"], "extra_cheese": false, "delivery": true, "client": { "proper name": "Jane Doe", "telephone": null, "email": "janedoe@email.com" } }, { "size": "small", "price": 6.54, "toppings": null, "extra_cheese": true, "delivery": false, "customer": { "name": "Foo Jones", "phone": "556-342-452", "email": null } } ] }
This is the new version in the orders_new.json
file:
{"orders": [{"size": "medium", "cost": fifteen.67, "toppings": ["mushrooms", "pepperoni", "basil"], "extra_cheese": false, "delivery": true}, {"size": "pocket-sized", "toll": 6.54, "toppings": zero, "extra_cheese": truthful, "commitment": false}]}
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 accept a moment to remember nearly this... What could information technology be?
Indentation, of course!
The file doesn't really look similar a JSON file, but we tin hands set up this past passing the statement indentation=four
to dump()
.

Now the content of the file looks like this:
{ "orders": [ { "size": "medium", "price": 15.67, "toppings": [ "mushrooms", "pepperoni", "basil" ], "extra_cheese": simulated, "delivery": true }, { "size": "small", "price": vi.54, "toppings": cipher, "extra_cheese": truthful, "commitment": false } ] }
What a difference! This is exactly what we would expect a JSON file to look like.
At present 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.
🔹 load() vs. loads()
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.
🔸 dump() vs. dumps()
Here we accept a table that summarizes the cardinal differences between these two functions:

💡 Tip: Remember of dumps()
every bit a "dump string" and that volition help you remember which function is used for which purpose.
🔹 Important Terminology in JSON
Finally, there are ii important terms that you demand to know to work with JSON:
- Serialization: converting an object into a JSON cord.
- Deserialization: converting a JSON string into an object.
🔸 In Summary
- JSON (JavaScript Object Notation) is a format used to correspond and store data.
- It is normally used to transfer information on the spider web and to store configuration settings.
- JSON files have a
.json
extension. - You can catechumen JSON strings into Python objects and vice versa.
- You lot can read JSON files and create Python objects from their key-value pairs.
- You can write to JSON files to store the content of Python objects in JSON format.
I really promise yous liked my commodity and found it helpful. Now y'all know how to work with JSON in Python. Follow me on Twitter @EstefaniaCassN and check out my online courses.
Learn to code for gratuitous. freeCodeCamp's open source curriculum has helped more than forty,000 people get jobs every bit developers. Get started
williamsgleir1983.blogspot.com
Source: https://www.freecodecamp.org/news/python-read-json-file-how-to-load-json-from-a-file-and-parse-dumps/
Enregistrer un commentaire for "Read Json Object and Save It in a Table Python"