How to Read Json Output in Python

Python Read JSON File – How to Load JSON from a File and Parse Dumps

Welcome! If you desire to learn how to work with JSON files in Python, then this article is for yous.

You will learn:

  • Why the JSON format is and 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-injson module.
  • How to convert JSON strings to Python objects and vice versa.
  • How to use loads() and dumps()
  • 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 prepare? Let'southward begin! ✨

πŸ”Ή Introduction: What is JSON?

image-98

The JSON format was originally inspired by the syntax of JavaScript (a programming language used for web development). But since and then information technology has become a language-independent data format and most of the programming languages that we use today can generate and read JSON.

Importance and Apply Cases of JSON

JSON is basically a format used to store or stand for data. Its mutual use cases include spider web development and configuration files.

Allow'southward see why:

  • Web Evolution: JSON is commonly used to send data from the server to the client and vice versa in web applications.
image-65
  • Configuration files: JSON is also used to store configurations and settings. For example, to create a Google Chrome App, y'all need to include a JSON file chosen manifest.json to specify the proper name of the app, its clarification, current version, and other backdrop and settings.
image-99

πŸ”Έ JSON Construction and Format

Now that you know what the JSON format is used for, let'south encounter its basic structure with an example that represents the information of a pizza guild:

                  {  	"size": "medium", 	"price": 15.67, 	"toppings": ["mushrooms", "pepperoni", "basil"], 	"extra_cheese": simulated, 	"delivery": true, 	"client": { 		"name": "Jane Doe", 		"phone": zippo, 		"e-mail": "janedoe@email.com" 	} }                
Sample .json file

These are the main characteristics of the JSON format:

  • There is a sequence of key-value pairs surrounded by curly brackets {}.
  • Each key is mapped to a detail value using this format:
                "key": <value>                              

πŸ’‘ Tip: The values that require quotes have to be surrounded past double quotes.

  • Key-value pairs are separated by a comma. Just the last pair is not followed past a comma.
                { 	"size": "medium", # Comma! 	"price": fifteen.67 }              

πŸ’‘ Tip: Nosotros typically format JSON with different levels of indentation to brand the data easier to read. In this commodity, you will acquire how to add the indentation automatically with Python.

JSON Information Types: Keys and Values

JSON files have specific rules that make up one's mind which data types are valid for keys and values.

  • Keys must exist strings.
  • Values can be either a string, a number, an array, a boolean value (truthful/ simulated), null, or a JSON object.

According to the Python Documentation:

Keys in primal/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.

Style Guide

According to the Google JSON Manner Guide:

  • Always choose meaningful names.
  • Array types should have plural central names. All other key names should exist singular. For example: use "orders" instead of "order" if the corresponding value is an array.
  • There should be no comments in JSON objects.

πŸ”Ή JSON vs. Python Dictionaries

JSON and Dictionaries might await very similar at starting time (visually), but they are quite unlike. Let'due south run across how they are "connected" and how they complement each other to brand Python a powerful tool to piece of work with JSON files.

JSON is a file format used to correspond and store data whereas a Python Dictionary is the bodily information construction (object) that is kept in memory while a Python program runs.

How JSON and Python Dictionaries Work Together

image-100

When we work with JSON files in Python, we can't just read them and utilise the data in our program directly. This is because the entire file would be represented as a single cord and we would not exist able to access the fundamental-value pairs individually.

Unless...

Nosotros use the key-value pairs of the JSON file to create a Python dictionary that nosotros tin can apply in our program to read the information, utilise it, and change information technology (if needed).

This is the principal connexion between JSON and Python Dictionaries. JSON is the string representation of the data and dictionaries are the actual information structures in retentiveness that are created when the program runs.

Smashing. Now that you know more than about JSON, let's start diving into the applied aspects of how you 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 you install Python and it includes functions to help you lot work with JSON files and strings.

We volition use this module in the coming examples.

How to Import the JSON Module

To use json in our program, nosotros just need to write an import statement at the height of the file.

Like this:

image-73

With this line, you volition have admission to the functions defined in the module. Nosotros will use several of them in the examples.

πŸ’‘ Tip: If y'all write this import statement, you will demand to utilize this syntax to call a role divers in the json module:

image-76

πŸ”Ή Python and JSON Strings

To illustrate how some of the most of import functions of the json module piece of work, nosotros will use a multi-line string with JSON format.

JSON String

Particularly, we will use this cord in the examples. It is just a regular multi-line Python string that follows the JSON format.

                  data_JSON =  """ { 	"size": "Medium", 	"cost": xv.67, 	"toppings": ["Mushrooms", "Extra Cheese", "Pepperoni", "Basil"], 	"customer": { 		"name": "Jane Doe", 		"phone": "455-344-234", 		"email": "janedoe@email.com" 	} } """                
JSON Cord
  • To define a multi-line cord in Python, nosotros utilise triple quotes.
  • Then, nosotros assign the cord to the variable data_JSON.

πŸ’‘ Tip: The Python Mode Guide recommends using double quote characters for triple-quoted strings.

JSON String to Python Dictionary

We will use the cord with JSON format to create a Python dictionary that nosotros tin admission, work with, and change.

To do this, nosotros will use the loads() function of the json module, passing the cord as the argument.

This is the bones syntax:

image-77

Here is the code:

                # Import the module import json  # String with JSON format data_JSON =  """ { 	"size": "Medium", 	"price": fifteen.67, 	"toppings": ["Mushrooms", "Actress Cheese", "Pepperoni", "Basil"], 	"client": { 		"name": "Jane Doe", 		"telephone": "455-344-234", 		"email": "janedoe@electronic mail.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 central-value pairs of the JSON cord and it returns this new dictionary.
  • Then, the lexicon returned is assigned to the variable data_dict.

Awesome! If nosotros print this dictionary, nosotros come across this output:

                {'size': 'Medium', 'toll': 15.67, 'toppings': ['Mushrooms', 'Actress 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 let's run into what happens when nosotros try to access the values of the fundamental-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["price"]) print(data_dict["toppings"]) print(data_dict["client"])              

The output is:

                Medium 15.67 ['Mushrooms', 'Actress Cheese', 'Pepperoni', 'Basil'] {'name': 'Jane Doe', 'phone': '455-344-234', 'email': 'janedoe@email.com'}              

Exactly what we expected. Each key can be used to access its corresponding value.

πŸ’‘ Tip: We can utilize this lexicon simply like any other Python dictionary. For example, nosotros can call dictionary methods, add, update, and remove key-value pairs, and more than. We can even apply it in a for loop.

JSON to Python: Blazon Conversion

When you employ loads() to create a Python lexicon from a JSON cord, you lot will notice that some values will exist converted into their respective 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:

image-79
Table presented in the official documentation of the json module

πŸ’‘ Tip: The aforementioned conversion table applies when we work with JSON files.

Python Dictionary to JSON String

Now you know how to create a Python dictionary from a string with JSON format.

But sometimes we might need to practise exactly the opposite, creating a string with JSON format from an object (for example, a dictionary) to print it, brandish it, store information technology, or work with information technology as a string.

To practice that, nosotros can employ the dumps role of the json module, passing the object every bit argument:

image-80

πŸ’‘ 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:

                # Python Lexicon client = {     "proper noun": "Nora",     "age": 56,     "id": "45355",     "eye_color": "green",     "wears_glasses": Faux }  # Go a JSON formatted string client_JSON = json.dumps(client)              

Let's focus on this line:

                client_JSON = json.dumps(client)              
  • json.dumps(client) creates and returns a string with all the fundamental-value pairs of the dictionary in JSON format.
  • Then, this string is assigned to the client_JSON variable.

If we impress this cord, we see this output:

                {"name": "Nora", "age": 56, "id": "45355", "eye_color": "green", "wears_glasses": false}              

πŸ’‘ Tip: Detect that the last value (imitation) was changed. In the Python dictionary, this value was Imitation but in JSON, the equivalent value is simulated. This helps u.s.a. confirm that, indeed, the original dictionary is now represented as a cord with JSON format.

If we bank check the data type of this variable, we run across:

                <class 'str'>              

So the return value of this part was definitely a string.

Python to JSON: Type Conversion

A process of blazon conversion occurs as well when we convert a dictionary into a JSON cord. This table from the Python Documentation illustrates the corresponding values:

image-81
Tabular array from the official documentation of the json module.

How to Print JSON With Indentation

If we use the dumps function and we print the cord that we got in the previous instance, we see:

                {"proper name": "Nora", "age": 56, "id": "45355", "eye_color": "greenish", "wears_glasses": false}              

But this is non very readable, right?

Nosotros can amend the readability of the JSON string past adding indentation.

To do this automatically, nosotros just need to pass a 2d argument to specify the number of spaces that we want to utilize to indent the JSON string:

image-111

πŸ’‘ Tip: the second argument has to exist a not-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 nosotros call dumps with this 2nd argument:

                client_JSON = json.dumps(client, indent=4)              

The result of printing client_JSON is:

                {     "proper name": "Nora",     "age": 56,     "id": "45355",     "eye_color": "green",     "wears_glasses": false }              

That'due south swell, right? Now our cord is nicely formatted. This volition be very helpful when nosotros start working with files to store the data in a human being-readable format.

How to Sort the Keys

You can too sort the keys in alphabetical order if you lot demand to. To do this, you just need to write the name of the parameter sort_keys and pass the value True:

image-84

πŸ’‘ Tip: The value of sort_keys is Imitation by default if you don't laissez passer a value.

For example:

                client_JSON = json.dumps(customer, sort_keys=Truthful)              

Returns this string with the keys sorted in alphabetical gild:

                {"age": 56, "eye_color": "green", "id": "45355", "name": "Nora", "wears_glasses": false}              

How to Sort Alphabetically and Indent (at the same fourth dimension)

To generate a JSON string that is sorted alphabetically and indented, you lot merely need to pass the 2 arguments:

image-104

In this example, the output is:

                {     "age": 56,     "eye_color": "green",     "id": "45355",     "proper noun": "Nora",     "wears_glasses": fake }              

πŸ’‘ Tip: You lot tin pass these arguments in whatever order (relative to each other), simply the object has to be the beginning argument in the listing.

Dandy. Now yous know how to work with JSON strings, so permit's see how yous tin can work with JSON files in your Python programs.

πŸ”Έ JSON and Files

Typically, JSON is used to store data in files, so Python gives u.s. the tools nosotros 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:

image-62

Permit'southward see how we can work with .json files in Python.

How to Read a JSON File in Python

Let's say that we created an orders.json file with this data that represents 2 orders in a pizza shop:

                  { 	"orders": [  		{ 			"size": "medium", 			"cost": 15.67, 			"toppings": ["mushrooms", "pepperoni", "basil"], 			"extra_cheese": fake, 			"delivery": true, 			"customer": { 				"name": "Jane Doe", 				"telephone": null, 				"electronic mail": "janedoe@electronic mail.com" 			} 		}, 		{ 			"size": "pocket-sized", 			"price": 6.54, 			"toppings": null, 			"extra_cheese": true, 			"delivery": imitation, 			"client": { 				"name": "Foo Jones", 				"telephone": "556-342-452", 				"email": naught 			} 		} 	] }                
orders.json

Please have a moment to analyze the structure of this JSON file.

Here are some quick tips:

  • Notice the data types of the values, the indentation, and the overall structure of the file.
  • The value of the main key "orders" is an array of JSON objects (this array volition be represented as listing in Python). Each JSON object holds the information of a pizza order.

If we want to read this file in Python, nosotros simply need to employ a with statement:

image-87

πŸ’‘ Tip: In the syntax above, we can assign any proper name to file (green box). This is a variable that we can 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 lexicon with the central-value pairs in the JSON file.
  • Then, this dictionary is assigned to the information variable.

πŸ’‘ Tip: Observe that nosotros are using load() instead of loads(). This is a dissimilar function in the json module. Y'all will learn more about their differences at the end of this commodity.

Once we have the content of the JSON file stored in the data variable as a dictionary, nosotros tin use it to exercise basically annihilation we want.

Examples

For example, if we write:

                impress(len(information["orders"]))              

The output is two considering the value of the master primal "orders" is a list with 2 elements.

We can also use the keys to admission their corresponding values. This is what nosotros typically exercise when we piece of work with JSON files.

For example, to access the toppings of the beginning order, we would write:

                information["orders"][0]["toppings"]              
  • First, we select the chief key "orders"
  • So, nosotros select the first chemical element in the list (index 0).
  • Finally, nosotros select the value that corresponds to the cardinal "toppings"

You lot can see this "path" graphically in the diagram:

image-101

If we print this value, the output is:

                ['mushrooms', 'pepperoni', 'basil']              

Exactly what nosotros expected. You just need to "dive deeper" into the structure of the dictionary by using the necessary keys and indices. You can apply the original JSON file/string as a visual reference. This way, you tin can admission, modify, or delete any value.

πŸ’‘ Tip: Remember that nosotros are working with the new dictionary. The changes fabricated to this dictionary will not bear on the JSON file. To update the content of the file, we need to write to the file.

How to Write to a JSON File

Let's see how you can write to a JSON file.

The offset line of the with statement is very similar. The simply change is that you lot need to open the file in 'w' (write) mode to be able to modify the file.

image-105

πŸ’‘ Tip: If the file doesn't exist already in the current working directory (folder), it will be created automatically. By using the 'w' style, nosotros volition exist replacing the entire content of the file if information technology already exists.

There are two alternative ways to write to a JSON file in the torso of the with statement:

  • dump
  • dumps

Allow'due south run into them in particular.

First Arroyo: dump

This is a office that takes two arguments:

  • The object that will be stored in JSON format (for example, a dictionary).
  • The file where it volition be stored (a file object).
image-91

Let's say that the pizza shop wants to remove the clients' data from the JSON file and create a new JSON file chosen orders_new.json with this new version.

We tin can practise this with this code:

                # Open up the orders.json file with open("orders.json") as file:     # Load its content and make a new dictionary     information = json.load(file)      # Delete the "client" key-value pair from each gild     for order in information["orders"]:         del order["client"]  # Open (or create) an orders_new.json file  # and shop the new version of the data. with open("orders_new.json", 'w') as file:     json.dump(data, file)              

This was the original version of the data in the orders.json file. Notice that the "customer" fundamental-value pair exists.

                  { 	"orders": [  		{ 			"size": "medium", 			"price": 15.67, 			"toppings": ["mushrooms", "pepperoni", "basil"], 			"extra_cheese": imitation, 			"delivery": true, 			"client": { 				"name": "Jane Doe", 				"phone": null, 				"email": "janedoe@email.com" 			} 		}, 		{ 			"size": "modest", 			"price": vi.54, 			"toppings": nil, 			"extra_cheese": true, 			"delivery": imitation, 			"customer": { 				"name": "Foo Jones", 				"telephone": "556-342-452", 				"email": zilch 			} 		} 	] }                                  
orders.json

This is the new version in the orders_new.json file:

                  {"orders": [{"size": "medium", "price": xv.67, "toppings": ["mushrooms", "pepperoni", "basil"], "extra_cheese": false, "commitment": true}, {"size": "modest", "price": 6.54, "toppings": null, "extra_cheese": true, "commitment": false}]}                
orders_new.json

If yous clarify this carefully, you volition see that the "clients" key-value pair was removed from all the orders.

Withal, there is something missing in this file, right?

Delight take a moment to think nearly this... What could information technology be?

Indentation, of form!

The file doesn't really look like a JSON file, but we can hands fix this by passing the statement indentation=4 to dump().

image-92

Now the content of the file looks like this:

                  {     "orders": [         {             "size": "medium",             "price": fifteen.67,             "toppings": [                 "mushrooms",                 "pepperoni",                 "basil"             ],             "extra_cheese": simulated,             "delivery": true         },         {             "size": "small",             "price": 6.54,             "toppings": naught,             "extra_cheese": true,             "delivery": false         }     ] }                
orders_new.json

What a difference! This is exactly what nosotros would expect a JSON file to look similar.

Now yous know how to read and write to JSON files using load() and dump(). Permit'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:

image-110

πŸ’‘ Tip: Recall of loads() as "load string" and that will help you call up which role is used for which purpose.

πŸ”Έ dump() vs. dumps()

Here nosotros have a tabular array that summarizes the key differences betwixt these two functions:

image-109

πŸ’‘ Tip: Call back of dumps() as a "dump cord" and that volition help you recollect which function is used for which purpose.

πŸ”Ή Important Terminology in JSON

Finally, in that location are two of import terms that you need 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 represent and store information.
  • It is commonly used to transfer data on the 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 tin can read JSON files and create Python objects from their central-value pairs.
  • You can write to JSON files to store the content of Python objects in JSON format.

I really hope y'all liked my article and found information technology helpful. At present you know how to work with JSON in Python. Follow me on Twitter @EstefaniaCassN and check out my online courses.



Acquire to code for free. freeCodeCamp's open source curriculum has helped more than than 40,000 people get jobs equally developers. Go started

snyderneverfunuty.blogspot.com

Source: https://www.freecodecamp.org/news/python-read-json-file-how-to-load-json-from-a-file-and-parse-dumps/

0 Response to "How to Read Json Output in Python"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel