JSON is an exceptional way to store and transfer data. Recently I wrote a primer on using JSON, and since we’ve also gone quite far down Python’s rabbit hole, I thought this would be a great way to tie it all together by demonstrating how you can leverage the power of JSON in Python.
Python has built-in support for JSON, through an aptly named JSON package, and treats JSON the same as dictionaries. In Python, JSON supports primitive types (such as strings and numbers) as well as nested lists, tuples, and objects.
But why would you use JSON in an already simple language like Python?
Simple. JSON is not only easy to understand, with its key:value pairs, but it is also widely used as a common data format for storing and retrieving data from APIs and configuration files. In other words, many other systems, applications, and services already use JSON to store and transfer data, so why wouldn’t you want to use it in Python?
That said, let’s find out how you can work with JSON in your Python code.
Hi world!
Yes, we are back to our favorite application, Hello world! We’ll create this simple application using good old Python and JSON.
The first thing we are going to do is create our Python script. Open a terminal window (I’m demoing on Linux with Python installed) and create the new file with the command:
nano hello-world.py
To use JSON in your Python code, the first thing you need to do is import the JSON library with the input:
Our next line contains the actual JSON input and looks like this:
sample_json = ‘{ “name1″:”Hello,” “name2″:”World!”}’
sample_json = ‘{ “name1″:”Hello,” “name2″:”World!”}’ |
Because we are using JSON, we have to work with a special function in the json library, called fillers. This will load the JSON data from sample_json and assign it to the variable Data. This line looks like this:
data = json.loads(sample_json)
Data = json.fillers(sample_json) |
Finally, we print the information we have stored in Data with the line:
print(f'{data[“name1”]} {Data[“name2”]}’)
to print(F‘{Data[“name1”]} {Data[“name2”]}’) |
Save and close the file. Run the application with the command:
You should see printed:
Hello, World!
Simple! Let’s complicate it a bit more. We’ll create a simple Python script that uses JSON as a dictionary, and then we’ll see how to print the data as unformatted and formatted results.
Create the new script with the command:
nano dict.py
Obviously, the first line will import the JSON library:
Next, we build our dictionary using JSON key:value pairs like this:
my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “The New Stack”, “specialty”: “Linux”, “emails”: [{“email”: “jack.wallen@example.com”, “type”: “work”}]”my_neighbor”: False }
My dictionary = { “Name”: “Jack Wallen”, “job title”: “Writer”, “Company Name”: “The New Stack”, “speciality”: “Linux”, “my neighbor”: Fake } |
Next, we will use the JSON dumps function on our my_dictionary object with the line:
unformatted_json = json.dumps(my_dictionary)
unformatted_json = json.dumps(My dictionary) |
Finally, we will print our JSON data unformatted with the line:
Our entire script looks like this:
import json my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “The New Stack”, “specialty”: “Linux”, “emails”: [{“email”: “jack.wallen@example.com”, “type”: “work”}]”my_neighbor”: False } unformatted_json = json. dumps(my_dictionary) print(unformatted_json)
import json My dictionary = { “Name”: “Jack Wallen”, “job title”: “Writer”, “Company Name”: “The New Stack”, “speciality”: “Linux”, “my neighbor”: Fake } unformatted_json = json.dumps(My dictionary) to print(unformatted_json) |
Save and close the file. Run it with:
python3 dict.py
The output of this application will look like this:
{“name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “The New Stack”, “specialty”: “Linux”, “emails”: [{“email”: “jack.wallen@example.com”, “type”: “work”}]”my_neighbor”: false}
{“Name”: “Jack Wallen”, “job title”: “Writer”, “Company Name”: “The New Stack”, “speciality”: “Linux”, “emails”: [{“email”: “[email protected]”, “type”: “work”}], “my neighbor”: fake}
|
Instead of printing unformatted text, we can actually print it in a more standard JSON format. To do this, we first need to add a section under the My dictionary section that looks like this:
formatted_json = json.dumps( my_dictionary, indent = 4, separators = (“”, “, “=”), sort_keys = True )
formatted_json = json.dumps( My dictionary, withdrawal = 4, separators = (“, “, “=”), sort_keys = True ) |
What the above section does is use the JSON flush function and then format My dictionary with dashes and double quote separators and also sorts the output dictionaries by key (with sort_keys = True), while assigning the data to the formatted_json variable.
Below this section, we then print the dictionary with the line:
Our entire script looks like this:
import json my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “The New Stack”, “specialty”: “Linux”, “emails”: [{“email”: “jack.wallen@example.com”, “type”: “work”}]”my_neighbor”: False } formatted_json = json.dumps( my_dictionary, indent = 4, separators = (“”, “, ” = “), sort_keys = True ) print(formatted_json)
1 2 3 4 5 6 7 8 9 ten 11 12 13 14 15 16 17 18 19 |
import json My dictionary = { “Name”: “Jack Wallen”, “job title”: “Writer”, “Company Name”: “The New Stack”, “speciality”: “Linux”, “my neighbor”: Fake } formatted_json = json.dumps( My dictionary, withdrawal = 4, separators = (“, “, “=”), sort_keys = True ) to print(formatted_json) |
Save and close the file. If you run the new script with:
python3 dict.py
The output should look like this:
{ “company_name” = “The new stack”, “emails” = [
{
“email” = “jack.wallen@example.com”,
“type” = “work”
}
]”job_title” = “Writer”, “my_neighbor” = false, “name” = “Jack Wallen”, “specialty” = “Linux” }
{ “Company Name” = “The New Stack”, “emails” = [ { “type” = “work” } ], “job title” = “Writer”, “my neighbor” = fake, “Name” = “Jack Wallen”, “speciality” = “Linux” } |
Read JSON from file
Suppose you have a long employee data file in JSON format. This file could be called data.json and look like this:
{ “Employee Details”: [
{
“employee_name” : “Jack Wallen”,
“employee_email” : “jack.wallen@example.com”,
“employee_title” : “writer”
},
{
“employee_name” : “Olivia Nightingale”,
“employee_email” : “olivia.nightingale@example.com”,
“employee_title” : “editor”
}
]}
{ “Employee Details”: [ { “employee_name” : “Jack Wallen”, “employee_title” : “writer” }, { “employee_name” : “Olivia Nightingale”, “employee_title” : “editor” } ] } |
We have information for two employees in JSON format.
Now our Python application (named read_data.py) to read this data might look like this (with comments for explanation):
# Import the JSON library import json # Open our JSON file named data.json f = open(‘data.json’) # return the JSON object as a dictionary data = json.load(f) # Iterate through the entire list data .json for me in data[’employee_details’]: print(i) # Close the data.json file f.close()
# Import JSON library import json # Open our JSON file named data.json F = to open(‘data.json’) # returns the JSON object as a dictionary Data = json.charge(F) # Iterate over the entire data.json list for I in Data[’employee_details’]: to print(I) # Close the data.json file F.close() |
Save and close the file. Run the application with the command:
python3 read_data.py
The application output will look like this:
{’employee_name’: ‘Jack Wallen’, ’employee_email’: ‘jack.wallen@example.com’, ’employee_title’: ‘writer’} {’employee_name’: ‘Olivia Nightingale’, ’employee_email’: ‘olivia.nightingale @example.com’, ’employee_title’: ‘editor’}
{‘Employee name’: “Jack Wallen”, ’employee_email’: ‘[email protected]’, ’employee_title’: ‘writer’}
{‘Employee name’: ‘Olivia Nightingale’, ’employee_email’: ‘[email protected]’, ’employee_title’: ‘editor’}
|
And There you go ! You used JSON in a Python application. As you can imagine, the possibilities are limitless with what you can do with this juxtaposition.