Json Command to Upload a File With Python

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

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

Yous will learn:

  • Why the JSON format is then important.
  • Its basic structure and data types.
  • How JSON and Python Dictionaries 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 y'all set? Let's begin! ✨

🔹 Introduction: What is JSON?

image-98

The JSON format was originally inspired by the syntax of JavaScript (a programming language used for spider web evolution). Only since then it has go a language-independent information format and most of the programming languages that we use today tin 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 utilize cases include web development and configuration files.

Let's come across why:

  • Web Development: JSON is commonly used to transport 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, yous need to include a JSON file chosen manifest.json to specify the name of the app, its description, current version, and other properties and settings.
image-99

🔸 JSON Construction and Format

Now that you know what the JSON format is used for, permit's come across its basic structure with an instance that represents the data of a pizza guild:

                  {  	"size": "medium", 	"toll": xv.67, 	"toppings": ["mushrooms", "pepperoni", "basil"], 	"extra_cheese": false, 	"commitment": true, 	"client": { 		"proper name": "Jane Doe", 		"phone": nil, 		"email": "janedoe@email.com" 	} }                
Sample .json file

These are the main characteristics of the JSON format:

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

💡 Tip: The values that require quotes have to be surrounded by double quotes.

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

💡 Tip: We typically format JSON with different levels of indentation to brand the data easier to read. In this article, you will larn how to add the indentation automatically with Python.

JSON Data Types: Keys and Values

JSON files have specific rules that determine which data types are valid for keys and values.

  • Keys must be strings.
  • Values tin be either a string, a number, an array, a boolean value (true/ fake), nil, or a JSON object.

According to the Python Documentation:

Keys in key/value pairs of JSON are ever of the type str. When a lexicon is converted into JSON, all the keys of the lexicon are coerced to strings.

Style Guide

According to the Google JSON Way Guide:

  • Always choose meaningful names.
  • Assortment types should take plural key names. All other key names should be singular. For example: use "orders" instead of "order" if the respective value is an assortment.
  • In that location should be no comments in JSON objects.

🔹 JSON vs. Python Dictionaries

JSON and Dictionaries might await very similar at first (visually), but they are quite different. Allow's see how they are "connected" and how they complement each other to make Python a powerful tool to piece of work with JSON files.

JSON is a file format used to represent and store data whereas a Python Dictionary is the actual data 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, nosotros can't just read them and use the information in our program directly. This is because the entire file would exist represented as a single string and we would not be able to admission the primal-value pairs individually.

Unless...

Nosotros apply the key-value pairs of the JSON file to create a Python dictionary that we tin use in our plan to read the information, employ it, and change it (if needed).

This is the main 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.

Peachy. Now that you know more nearly JSON, let's starting time diving into the practical aspects of how you tin work with JSON in Python.

🔸 The JSON Module

Luckily for us, Python comes with a built-in module called json. It is installed automatically when you install Python and information technology includes functions to assistance you work with JSON files and strings.

We will apply this module in the coming examples.

How to Import the JSON Module

To utilize json in our program, we just need to write an import statement at the top of the file.

Similar this:

image-73

With this line, y'all will have access to the functions defined in the module. Nosotros volition use several of them in the examples.

💡 Tip: If y'all write this import statement, you will need to use this syntax to phone call a part defined in the json module:

image-76

🔹 Python and JSON Strings

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

JSON String

Peculiarly, we volition utilize this string in the examples. It is just a regular multi-line Python string that follows the JSON format.

                  data_JSON =  """ { 	"size": "Medium", 	"toll": 15.67, 	"toppings": ["Mushrooms", "Actress Cheese", "Pepperoni", "Basil"], 	"client": { 		"name": "Jane Doe", 		"telephone": "455-344-234", 		"e-mail": "janedoe@electronic mail.com" 	} } """                
JSON String
  • To define a multi-line string in Python, we utilise triple quotes.
  • So, we assign the cord to the variable data_JSON.

💡 Tip: The Python Style Guide recommends using double quote characters for triple-quoted strings.

JSON String to Python Dictionary

We will use the string with JSON format to create a Python lexicon that we can access, work with, and modify.

To do this, we will apply the loads() office of the json module, passing the string every bit the argument.

This is the basic syntax:

image-77

Hither 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 name": "Jane Doe", 		"phone": "455-344-234", 		"email": "janedoe@electronic mail.com" 	} } """  # Convert JSON string to dictionary data_dict = json.loads(data_JSON)                              

Let'south focus on this line:

                data_dict = json.loads(data_JSON)              
  • json.loads(data_JSON) creates a new dictionary with the primal-value pairs of the JSON string and information technology returns this new dictionary.
  • Then, the dictionary returned is assigned to the variable data_dict.

Awesome! If nosotros print this dictionary, we see this output:

                {'size': 'Medium', 'toll': 15.67, 'toppings': ['Mushrooms', 'Extra Cheese', 'Pepperoni', 'Basil'], 'customer': {'name': 'Jane Doe', 'phone': '455-344-234', 'electronic mail': 'janedoe@email.com'}}              

The dictionary has been populated with the data of the JSON string. Each key-value pair was added successfully.

Now let'due south encounter what happens when we endeavour to access the values of the key-value pairs with the aforementioned syntax that we 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 xv.67 ['Mushrooms', 'Extra Cheese', 'Pepperoni', 'Basil'] {'name': 'Jane Doe', 'phone': '455-344-234', 'e-mail': 'janedoe@email.com'}              

Exactly what nosotros expected. Each key can be used to admission its corresponding value.

💡 Tip: Nosotros can utilize this dictionary just like any other Python dictionary. For example, we can telephone call dictionary methods, add together, update, and remove key-value pairs, and more. We tin even use it in a for loop.

JSON to Python: Blazon Conversion

When you utilize loads() to create a Python dictionary from a JSON string, you will observe that some values will be converted into their corresponding Python values and data types.

This tabular array presented in the Python Documentation for the json module summarizes the correspondence from JSON information 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 Cord

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 lexicon) to print it, display information technology, shop it, or piece of work with it every bit a string.

To exercise that, we can use the dumps function 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 catechumen the Python dictionary customer into a string with JSON format and store information technology in a variable:

                # Python Lexicon client = {     "name": "Nora",     "age": 56,     "id": "45355",     "eye_color": "dark-green",     "wears_glasses": False }  # Get a JSON formatted cord client_JSON = json.dumps(customer)              

Allow'due south focus on this line:

                client_JSON = json.dumps(client)              
  • json.dumps(client) creates and returns a cord 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, we see this output:

                {"proper noun": "Nora", "historic period": 56, "id": "45355", "eye_color": "greenish", "wears_glasses": false}              

💡 Tip: Notice that the last value (false) was changed. In the Python dictionary, this value was Faux only in JSON, the equivalent value is false. This helps us confirm that, indeed, the original dictionary is now represented equally a cord with JSON format.

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

                <form 'str'>              

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

Python to JSON: Type Conversion

A procedure of type conversion occurs also when nosotros catechumen a dictionary into a JSON string. This table from the Python Documentation illustrates the corresponding values:

image-81
Table from the official documentation of the json module.

How to Print JSON With Indentation

If we use the dumps function and we impress the string that we got in the previous example, we see:

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

Just this is not very readable, right?

We tin amend the readability of the JSON string past adding indentation.

To practise this automatically, we just demand to pass a second argument to specify the number of spaces that we want to use 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 cord is used to indent each level (source).

Now, if we call dumps with this second argument:

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

The event of printing client_JSON is:

                {     "proper noun": "Nora",     "historic period": 56,     "id": "45355",     "eye_color": "light-green",     "wears_glasses": false }              

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.

How to Sort the Keys

You can also sort the keys in alphabetical guild if you need to. To exercise this, you lot 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 Fake by default if you don't pass a value.

For example:

                client_JSON = json.dumps(client, sort_keys=True)              

Returns this string with the keys sorted in alphabetical guild:

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

How to Sort Alphabetically and Indent (at the same time)

To generate a JSON string that is sorted alphabetically and indented, you just need to pass the ii arguments:

image-104

In this example, the output is:

                {     "age": 56,     "eye_color": "dark-green",     "id": "45355",     "proper noun": "Nora",     "wears_glasses": false }              

💡 Tip: You tin can pass these arguments in any order (relative to each other), but the object has to be the get-go argument in the listing.

Great. Now you know how to work with JSON strings, so let's see how you tin 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 nosotros demand to read these types of file in our program, work with their information, and write new data.

💡 Tip: a JSON file has a .json extension:

image-62

Allow's see how nosotros 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 information that represents two orders in a pizza store:

                  { 	"orders": [  		{ 			"size": "medium", 			"price": 15.67, 			"toppings": ["mushrooms", "pepperoni", "basil"], 			"extra_cheese": false, 			"commitment": true, 			"client": { 				"name": "Jane Doe", 				"phone": zippo, 				"email": "janedoe@e-mail.com" 			} 		}, 		{ 			"size": "small", 			"toll": 6.54, 			"toppings": zippo, 			"extra_cheese": true, 			"delivery": false, 			"client": { 				"name": "Foo Jones", 				"phone": "556-342-452", 				"email": naught 			} 		} 	] }                
orders.json

Delight take a moment to clarify the structure of this JSON file.

Here are some quick tips:

  • Detect 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 will be represented equally listing in Python). Each JSON object holds the data of a pizza social club.

If we want to read this file in Python, we only demand to employ a with statement:

image-87

💡 Tip: In the syntax in a higher place, we tin assign whatever name to file (green box). This is a variable that nosotros tin can utilise inside the with statement to refer to the file object.

The key line of lawmaking 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.
  • Then, this dictionary is assigned to the data variable.

💡 Tip: Notice that we are using load() instead of loads(). This is a different function in the json module. Yous volition larn more than about their differences at the end of this article.

In one case we have the content of the JSON file stored in the information variable equally a dictionary, nosotros can utilize it to practice basically anything we want.

Examples

For example, if we write:

                print(len(data["orders"]))              

The output is 2 because the value of the main key "orders" is a list with two elements.

Nosotros can likewise use the keys to admission their corresponding values. This is what we typically do when we work with JSON files.

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

                data["orders"][0]["toppings"]              
  • Start, nosotros select the main key "orders"
  • Then, we select the first element in the listing (index 0).
  • Finally, we select the value that corresponds to the key "toppings"

Yous tin can run into this "path" graphically in the diagram:

image-101

If we print this value, the output is:

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

Exactly what nosotros expected. Y'all just need to "dive deeper" into the construction of the dictionary by using the necessary keys and indices. You tin can use the original JSON file/string as a visual reference. This way, you tin can access, change, 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.

How to Write to a JSON File

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

The first line of the with statement is very similar. The only modify is that you need to open up the file in 'west' (write) mode to be able to alter the file.

image-105

💡 Tip: If the file doesn't exist already in the current working directory (folder), it volition be created automatically. Past using the 'w' fashion, we will exist replacing the entire content of the file if it already exists.

In that location are 2 alternative ways to write to a JSON file in the torso of the with argument:

  • dump
  • dumps

Let'due south run across them in particular.

Start Approach: dump

This is a function that takes two arguments:

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

Permit's say that the pizza store 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 exercise this with this code:

                # Open the orders.json file with open("orders.json") as file:     # Load its content and brand a new lexicon     information = json.load(file)      # Delete the "customer" key-value pair from each social club     for order in data["orders"]:         del order["customer"]  # Open up (or create) an orders_new.json file  # and shop the new version of the information. 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 "client" fundamental-value pair exists.

                  { 	"orders": [  		{ 			"size": "medium", 			"price": 15.67, 			"toppings": ["mushrooms", "pepperoni", "basil"], 			"extra_cheese": false, 			"delivery": true, 			"client": { 				"name": "Jane Doe", 				"telephone": zilch, 				"email": "janedoe@email.com" 			} 		}, 		{ 			"size": "small", 			"price": half dozen.54, 			"toppings": goose egg, 			"extra_cheese": true, 			"commitment": imitation, 			"client": { 				"name": "Foo Jones", 				"phone": "556-342-452", 				"electronic mail": zero 			} 		} 	] }                                  
orders.json

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

                  {"orders": [{"size": "medium", "cost": 15.67, "toppings": ["mushrooms", "pepperoni", "basil"], "extra_cheese": fake, "delivery": true}, {"size": "small", "price": vi.54, "toppings": null, "extra_cheese": true, "delivery": imitation}]}                
orders_new.json

If you analyze this carefully, you lot will run into that the "clients" key-value pair was removed from all the orders.

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

Please have a moment to think most this... What could it be?

Indentation, of course!

The file doesn't really look similar a JSON file, but we tin can hands ready this by passing the argument indentation=4 to dump().

image-92

Now the content of the file looks similar this:

                  {     "orders": [         {             "size": "medium",             "price": 15.67,             "toppings": [                 "mushrooms",                 "pepperoni",                 "basil"             ],             "extra_cheese": false,             "delivery": truthful         },         {             "size": "small-scale",             "cost": vi.54,             "toppings": zero,             "extra_cheese": true,             "delivery": false         }     ] }                
orders_new.json

What a difference! This is exactly what we would expect a JSON file to look like.

Now y'all know how to read and write to JSON files using load() and dump(). Permit's run across the differences betwixt these functions and the functions that we used to piece of work with JSON strings.

🔹 load() vs. loads()

This table summarizes the cardinal differences between these two functions:

image-110

💡 Tip: Think of loads() as "load cord" and that will help you call up which function is used for which purpose.

🔸 dump() vs. dumps()

Hither we accept a tabular array that summarizes the key differences between these two functions:

image-109

💡 Tip: Think of dumps() as a "dump string" and that will help you call back which function is used for which purpose.

🔹 Of import Terminology in JSON

Finally, there are 2 important terms that you demand to know to work with JSON:

  • Serialization: converting an object into a JSON string.
  • Deserialization: converting a JSON cord into an object.

🔸 In Summary

  • JSON (JavaScript Object Notation) is a format used to stand for and store data.
  • It is commonly used to transfer data on the web and to store configuration settings.
  • JSON files have a .json extension.
  • You lot can convert JSON strings into Python objects and vice versa.
  • You can read JSON files and create Python objects from their key-value pairs.
  • You tin write to JSON files to store the content of Python objects in JSON format.

I really hope y'all liked my commodity and plant it helpful. Now you lot know how to work with JSON in Python. Follow me on Twitter @EstefaniaCassN and check out my online courses.



Learn to code for costless. freeCodeCamp'south open up source curriculum has helped more than 40,000 people become jobs equally developers. Get started

williamsraiddece99.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 "Json Command to Upload a File With Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel