VOOZH about

URL: https://thenewstack.io/python-for-beginners-how-to-use-json-in-python/

⇱ Python for Beginners: How to Use JSON in Python - The New Stack


TNS
SUBSCRIBE
Join our community of software engineering leaders and aspirational developers. Always stay in-the-know by getting the most important news and exclusive content delivered fresh to your inbox to learn more about at-scale software development.
REQUIRED
It seems that you've previously unsubscribed from our newsletter in the past. Click the button below to open the re-subscribe form in a new tab. When you're done, simply close that tab and continue with this form to complete your subscription.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.
Welcome and thank you for joining The New Stack community!
Please answer a few simple questions to help us deliver the news and resources you are interested in.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Great to meet you!
Tell us a bit about your job so we can cover the topics you find most relevant.
REQUIRED
REQUIRED
REQUIRED
REQUIRED
REQUIRED
Welcome!

We’re so glad you’re here. You can expect all the best TNS content to arrive Monday through Friday to keep you on top of the news and at the top of your game.

What’s next?

Check your inbox for a confirmation email where you can adjust your preferences and even join additional groups.

Follow TNS on your favorite social media networks.

Become a TNS follower on LinkedIn.

Check out the latest featured and trending stories while you wait for your first TNS newsletter.

PREV
1 of 2
NEXT
VOXPOP
As a JavaScript developer, what non-React tools do you use most often?
Angular
0%
Astro
0%
Svelte
0%
Vue.js
0%
Other
0%
I only use React
0%
I don't use JavaScript
0%
Thanks for your opinion! Subscribe below to get the final results, published exclusively in our TNS Update newsletter:
NEW! Try Stackie AI
From clobbered drafts to real-time sync
Apr 14th 2026 10:00am, by David Moore
TypeScript 6.0 RC arrives as a bridge to a faster future
Mar 14th 2026 9:00am, by Darryl K. Taft
Mastra empowers web devs to build AI agents in TypeScript
Jan 28th 2026 11:00am, by Loraine Lawson
2022-05-01 05:00:06
Python for Beginners: How to Use JSON in Python
tutorial,
Data / Python / Software Development

Python for Beginners: How to Use JSON in Python

How to parse JSON files within a Python program.
May 1st, 2022 5:00am by Jack Wallen
👁 Featued image for: Python for Beginners: How to Use JSON in Python

JSON is an outstanding way of storing and transferring data. Recently, I wrote an introduction on how to use JSON, and given we’ve also gone pretty deep down the rabbit hole of Python, I thought it would be a great way to tie this all together by demonstrating how you can leverage the power of JSON within Python.

Python has built-in support for JSON, via a package aptly named JSON, and treats JSON similarly to dictionaries. Within 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 easy language such as Python?

Simple. JSON is not only easy to comprehend, with its key:value pairs, but it’s also very often used as a common data format for storing and fetching data from APIs and config files. In other words, a lot of other systems, applications and services already use JSON to store and transfer data, so why wouldn’t you want to use it in Python?

With that said, let’s find out how you can work with JSON inside of your Python code.

Hello, World!

Yep, we’re back to our favorite application, Hello world! We’re going to create this easy application using good ol’ Python and JSON.

The first thing we’ll do is create our Python script. Open a terminal window (I’m demonstrating 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 we must do is import the JSON library with the entry:

import json

Our next line contains the actual JSON entry and looks like this:

sample_json =  '{ "name1":"Hello,", "name2":"World!"}'

Because we’re using JSON, we have to work with a special function in the json library, called loads. What this will do is load the JSON data from sample_json and assign it to the variable data. This line looks like this:

data = json.loads(sample_json)

Finally, we print the information we’ve stored in data with the line:

print(f'{data["name1"]} {data["name2"]}')

Save and close the file. Run the app with the command:

python3 hello-world.py

You should see printed out:

Hello, World!

Simple! Let’s get a bit more complicated. We’ll create a simple Python script that uses JSON as a dictionary and then we’ll see how we can print the data as both unformatted and formatted results.

Create the new script with the command:

nano dict.py

Obviously, the first line will import the JSON library:

import json

Next, we build our dictionary using JSON key:value pairs like so:

my_dictionary = {
"name": "Jack Wallen",
"job_title": "Writer",
"company_name": "The New Stack",
"speciality": "Linux",
"emails": [{"email": "jack.wallen@example.com", "type": "work"}],
"my_neighbor": False
}

Next, we’ll use the dumps function from JSON on our my_dictionary object with the line:

unformatted_json = json.dumps(my_dictionary)

Finally, we’ll print our JSON data in an unformatted fashion with the line:

print(unformatted_json)

Our entire script looks like this:

import json

my_dictionary = {
    "name": "Jack Wallen",
    "job_title": "Writer",
    "company_name": "The New Stack",
    "speciality": "Linux",
    "emails": [{"email": "jack.wallen@example.com", "type": "work"}],
    "my_neighbor": False
}

unformatted_json = json.dumps(my_dictionary)
print(unformatted_json)

Save and close the file. Run it with:

python3 dict.py

The output of this app will look something like this:

{"name": "Jack Wallen", "job_title": "Writer", "company_name": "The New Stack", "speciality": "Linux", "emails": [{"email": "jack.wallen@example.com", "type": "work"}], "my_neighbor": false}

Instead of printing out unformatted text, we can actually print it out in a more standard JSON format. To do that, we have to first add a section under the my_dictionary section that looks like this:

formatted_json = json.dumps(
  my_dictionary,
  indent = 4,
  separators = (", ", " = "),
  sort_keys = True
)

What the above section does is use the dumps function from JSON and then formats my_dictionary with indents and double-quote separators and also sorts the output dictionaries by key (with sort_keys = True), all the while assigning the data to the formatted_json variable.

Under that section, we then print the dictionary with the line:

print(formatted_json)

Our entire script looks like this:

import json  

my_dictionary = {
    "name": "Jack Wallen",
    "job_title": "Writer",
    "company_name": "The New Stack",
    "speciality": "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)

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",
    "speciality" = "Linux"
}

Read JSON from a File

Let’s say you have a long JSON-formatted file of employee data. That file might 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"
            }
     ]
}

We have information for two employees laid out in JSON format.

Now, our Python app (named read_data.py) to read in that data might look something like this (with comments for explanation):

# Import the JSON library
import json

# Open our JSON file named data.json
f = open('data.json')

# returns JSON object as a dictionary
data = json.load(f)

# Iterate through the entire data.json list
for i in data['employee_details']:
    print(i)

# Close the data.json file
f.close()

Save and close the file. Run the app with the command:

python3 read_data.py

The output of the app will look something 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'}

And there you go! You’ve used JSON within a Python application. As you might imagine, the possibilities are limitless with what you can do with this juxtaposition.

TRENDING STORIES
Jack Wallen is what happens when a Gen Xer mind-melds with present-day snark. Jack is a seeker of truth and a writer of words with a quantum mechanical pencil and a disjointed beat of sound and soul. Although he resides...
Read more from Jack Wallen
SHARE THIS STORY
TRENDING STORIES
TNS owner Insight Partners is an investor in: Writer.
SHARE THIS STORY
TRENDING STORIES
TNS DAILY NEWSLETTER Receive a free roundup of the most recent TNS articles in your inbox each day.
The New Stack does not sell your information or share it with unaffiliated third parties. By continuing, you agree to our Terms of Use and Privacy Policy.