- Home
- >
- Software Development
- >
- How to Use JSON in Python – InApps Technology 2025
How to Use JSON in Python – InApps Technology is an article under the topic Software Development Many of you are most interested in today !! Today, let’s InApps.net learn How to Use JSON in Python – InApps Technology in today’s post !
Key Summary
The article from InApps.net provides a beginner-friendly guide to using JSON in Python, leveraging the built-in json library to handle data storage and transfer. JSON, with its key:value pair structure, is widely used for APIs and config files, making it a valuable tool in Python for interoperability with other systems. Key points include:
- Why Use JSON in Python:
- JSON is easy to understand, supports primitive types (strings, numbers) and complex structures (nested lists, tuples, objects).
- Commonly used for data exchange in APIs, config files, and other systems, enhancing Python’s utility.
- Prerequisites:
- Python installed (demonstrated on Linux, but applicable to macOS/Windows).
- A text editor (e.g., nano).
- Basic Example: Hello, World!:
- Create hello-world.py:
python
CollapseWrapRun
Copy
- Create hello-world.py:
import json
sample_json = ‘{“message”: “Hello, World!”}’
data = json.loads(sample_json)
- print(data[‘message’])
- Run with python3 hello-world.py to output: Hello, World!
- Uses json.loads() to parse JSON string into a Python dictionary.
- Using JSON as a Dictionary:
- Create dict.py to build and format a JSON dictionary:
python
CollapseWrapRun
Copy
- Create dict.py to build and format a JSON dictionary:
import json
my_dictionary = {
“name”: “Jack”,
“age”: 30,
“city”: “New York”
}
unformatted_json = json.dumps(my_dictionary)
print(unformatted_json)
formatted_json = json.dumps(my_dictionary, indent=4, separators=(“,”, “: “), sort_keys=True)
- print(formatted_json)
- Run with python3 dict.py to output:
- Unformatted: {“name”: “Jack”, “age”: 30, “city”: “New York”}
- Formatted:
json
CollapseWrap
Copy
{
“age”: 30,
“city”: “New York”,
“name”: “Jack”
- }
- Uses json.dumps() to serialize dictionary to JSON string; indent, separators, and sort_keys improve readability.
- Reading JSON from a File:
- Create data.json with employee data:
json
CollapseWrap
Copy
- Create data.json with employee data:
[
{
“name”: “Jack”,
“age”: 30,
“city”: “New York”
},
{
“name”: “Jill”,
“age”: 25,
“city”: “Los Angeles”
}
- ]
- Create read_data.py to read and process the file:
python
CollapseWrapRun
Copy
import json
# Open JSON file
with open(‘data.json’) as file:
# Load JSON data into Python object
data = json.load(file)
# Iterate over the list of employees
for employee in data:
print(f”Name: {employee[‘name’]}“)
print(f”Age: {employee[‘age’]}“)
print(f”City: {employee[‘city’]}“)
- print(“-“ * 20)
- Run with python3 read_data.py to output:
text
CollapseWrap
Copy
Name: Jack
Age: 30
City: New York
——————–
Name: Jill
Age: 25
City: Los Angeles
- ——————–
- Uses json.load() to read JSON file directly into a Python object.
- Key Takeaways:
- Python’s json library simplifies working with JSON data, treating it like dictionaries.
- Functions like loads(), dumps(), load() enable parsing, serializing, and file operations.
- JSON’s versatility in Python supports diverse applications, from API integration to data storage.
Read more about How to Use JSON in Python – InApps Technology at Wikipedia
You can find content about How to Use JSON in Python – InApps Technology from the Wikipedia website
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:
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:
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:
Next, we build our dictionary using JSON key:value pairs like so:
my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “InApps Technology”, “speciality”: “Linux”, “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:
Our entire script looks like this:
<br />
my_dictionary = {
<br />
“name”: “Jack Wallen”,
<br />
“job_title”: “Writer”,
<br />
“company_name”: “InApps Technology”,
<br />
“speciality”: “Linux”,
<br />
“emails”: [{“email”: “jack.wallen@example.com”, “type”: “work”}],
<br />
“my_neighbor”: False
<br />
}
<br />
<br />
unformatted_json = json.dumps(my_dictionary)
<br />
print(unformatted_json)
import json my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “InApps Technology”, “speciality”: “Linux”, “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”: “InApps Technology”, “speciality”: “Linux”, “emails”: [{“email”: “[email protected]”, “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:
Our entire script looks like this:
<br />
my_dictionary = {
<br />
“name”: “Jack Wallen”,
<br />
“job_title”: “Writer”,
<br />
“company_name”: “InApps Technology”,
<br />
“speciality”: “Linux”,
<br />
“emails”: [{“email”: “jack.wallen@example.com”, “type”: “work”}],
<br />
“my_neighbor”: False
<br />
}
<br />
<br />
formatted_json = json.dumps(
<br />
my_dictionary,
<br />
indent = 4,
<br />
separators = (“, “, ” = “),
<br />
sort_keys = True
<br />
)
<br />
<br />
print(formatted_json)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import json my_dictionary = { “name”: “Jack Wallen”, “job_title”: “Writer”, “company_name”: “InApps Technology”, “speciality”: “Linux”, “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” = “InApps Technology”, “emails” = [ { “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_title” : “writer” }, { “employee_name” : “Olivia Nightingale”, “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):
<br />
# Open our JSON file named data.json
<br />
f = open(‘data.json’)
<br />
<br />
# returns JSON object as a dictionary
<br />
data = json.load(f)
<br />
<br />
# Iterate through the entire data.json list
<br />
for i in data[’employee_details’]:
<br />
print(i)
<br />
<br />
# Close the data.json file
<br />
f.close()
# 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’: ‘[email protected]’, ’employee_title’: ‘writer’}
{’employee_name’: ‘Olivia Nightingale’, ’employee_email’: ‘[email protected]’, ’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.
Source: InApps.net
Let’s create the next big thing together!
Coming together is a beginning. Keeping together is progress. Working together is success.