[Python] JSON Module Primer! Master the Essential Data Format for Web Development
To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you havenโt installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
Hello! I'm sharing the knowledge I gained in the process of launching a website from scratch with the help of AI, even though I didn't know the first thing about programming just a few months ago.
What comes to mind when you hear "JSON"? You might think, "It sounds complicated..." or "That's for web experts, right?" I felt the same way at first. But when it comes to web development, especially for creating modern "dynamic sites," JSON is an unavoidable and incredibly reliable partner once you get to know it.
In this article, I'll explain how to masterfully handle JSON data using Python's json module in the clearest way possible, sharing the points where I actually got stuck. The goal is for you to be able to get hands-on and truly feel "Ah, so this is how you use JSON!" by the time you finish reading. I've prepared plenty of "working code" that you can copy and paste, so let's experience that "It works!" moment together!
What on Earth is JSON? And Why is it Necessary for Web Development?
Let's set aside the difficult definitions for a moment. To put it very simply, JSON is a "common language for different programs to exchange information."
For example, let's say Mr. Python, running on your website's backend (the server), has user profile information (name, age, hobbies, etc.). You want to pass that information to Mr. JavaScript, running on the frontend (the browser) that the user sees, to display a neat profile card.
- Mr. Python translates the information he has into the universal language of "JSON" and passes it along.
- Mr. JavaScript receives that JSON and translates it back into a language he understands.
- The information is successfully transmitted, and the profile card is displayed!
In this way, JSON is an indispensable "bridge" for data exchange between the server-side and the front-end. When you fetch data like weather forecasts or news articles from a Web API (a mechanism for getting data from external services), this JSON format is used almost 100% of the time. Convenient, right?
The 4 Basic Magic Spells for Handling JSON in Python
Python comes with a standard module called json to handle this convenient format right out of the box. No pip install is needed; you can use it immediately just by writing import json.
This module has many features, but as a beginner, you only need to remember the following four functions (magic spells) to start!
json.dumps(): Converts Python data (like a dictionary) into a JSON-formatted "string."json.loads(): Converts a JSON-formatted "string" into Python data.json.dump(): Writes Python data to a JSON "file."json.load(): Reads a JSON "file" and converts it into Python data.
Thinking, "Ugh, the similar names are confusing!"? It's okay, I thought so too (lol). There's an easy way to remember them.
Just remember that the ones with an s at the end (dumps, loads) are for handling Strings. The ones without the s handle files directly. Now you won't get confused anymore!
1. Converting Python Data to a JSON String: json.dumps()
First, let's try converting a Python dictionary (dict) into a JSON-formatted string. This is the absolute basic.
# python-code
import json
# Python dictionary data
user_data = {
"name": "CopiCode Taro",
"age": 30,
"is_creator": True,
"skills": ["HTML", "CSS", "JavaScript", "Python"]
}
# Convert the Python dictionary to a JSON string
json_string = json.dumps(user_data)
print(json_string)
# Let's also check the type
print(type(json_string))
Execution Result:
{"name": "CopiCode Taro", "age": 30, "is_creator": true, "skills": ["HTML", "CSS", "JavaScript", "Python"]}
<class 'str'>
[Stumbling Block #1] Non-English Characters Look Like `\uXXXX`!
If you looked at the result above and thought, "Hey, why does the name look like weird symbols?", you have a great eye for detail. This is a type of "garbled text," and it's something I got really stuck on at first.
The reason is that json.dumps() by default escapes any non-ASCII characters (basically, characters other than standard English letters and numbers). To fix this, you add a little magic spell: ensure_ascii=False.
# python-code
import json
user_data = {
"name": "CopiCode Taro",
"age": 30,
"is_creator": True,
"skills": ["HTML", "CSS", "JavaScript", "Python"]
}
# Add ensure_ascii=False to output non-ASCII characters as is
json_string_jp = json.dumps(user_data, ensure_ascii=False)
print(json_string_jp)
Execution Result:
{"name": "CopiCode Taro", "age": 30, "is_creator": true, "skills": ["HTML", "CSS", "JavaScript", "Python"]}
Success, the name is now displayed correctly! If you're building services for a non-English audience, this ensure_ascii=False is an almost essential partner.
[Stumbling Block #2] The JSON is a Hard-to-Read Single Line!
Another problem. As your data gets bigger, it all gets crammed into a single line, making it very difficult to read. This can also be solved with an option. Specifying indent will add line breaks and indentation to make it human-readable. The number represents the number of spaces, and 4 is commonly used.
# python-code
import json
user_data = {
"name": "CopiCode Taro",
"age": 30,
"is_creator": True,
"skills": ["HTML", "CSS", "JavaScript", "Python"]
}
# Specify both ensure_ascii=False and indent=4
json_string_pretty = json.dumps(user_data, ensure_ascii=False, indent=4)
print(json_string_pretty)
Execution Result:
{
"name": "CopiCode Taro",
"age": 30,
"is_creator": true,
"skills": [
"HTML",
"CSS",
"JavaScript",
"Python"
]
}
What do you think? It's much easier to read now, right? These two options are often used together, so be sure to remember them. The official Python documentation also explains these options in detail.
2. Converting a JSON String Back to Python Data: json.loads()
Next is the reverse operation. Let's convert a JSON-formatted "string" received from a Web API or elsewhere back into a Python dictionary that we can work with. We'll use loads, the one with the `s`.
# python-code
import json
# Assume a string like this is received from a Web API
received_json_string = """
{
"id": "001",
"productName": "Awesome Keyboard",
"price": 15800,
"inStock": true
}
"""
# Convert the JSON string to a Python dictionary
product_data = json.loads(received_json_string)
print(product_data)
# Let's also check the type
print(type(product_data))
# Now that it's a dictionary, we can access values by key
print(f"Product Name: {product_data['productName']}")
print(f"Price: {product_data['price']} JPY")
Execution Result:
{'id': '001', 'productName': 'Awesome Keyboard', 'price': 15800, 'inStock': True}
<class 'dict'>
Product Name: Awesome Keyboard
Price: 15800 JPY
The JSON string was brilliantly converted into a Python dictionary (dict)! Now we can freely process the data or extract just the information we need.
3. Writing Python Data to a JSON File: json.dump()
Next up is file operations. We'll use dump() without the `s`. This is often used to save website settings or processing results to a file.
dump() takes two arguments. The first is the Python data you want to write, and the second is a file object. Using the with open(...) syntax is the safe and common way to do this.
# python-code
import json
# Settings data to save
app_settings = {
"theme": "dark",
"language": "english",
"notifications": {
"email": True,
"push": False
},
"version": "1.0.2"
}
# 'w' means write mode
# Specifying encoding='utf-8' is good practice when including non-ASCII characters
with open('settings.json', 'w', encoding='utf-8') as f:
# indent and ensure_ascii can be used here too
json.dump(app_settings, f, indent=4, ensure_ascii=False)
print("Wrote settings to settings.json file.")
When you run this code, a file named settings.json will be created in the same directory as your Python script. Its content should be in the same easy-to-read format as when we used dumps with indentation.
4. Reading a JSON File into Python Data: json.load()
Finally, let's read the settings.json file we just created. Since it's a file operation, we'll use load() without the `s`.
# python-code
import json
import os # Import the os module to check for file existence
file_path = 'settings.json'
# Check if the file exists
if os.path.exists(file_path):
# 'r' means read mode
with open(file_path, 'r', encoding='utf-8') as f:
# Just pass the file object
loaded_settings = json.load(f)
print("Loaded settings from settings.json.")
print(loaded_settings)
# Process the loaded data
print(f"Current theme setting: {loaded_settings['theme']}")
else:
print(f"Error: {file_path} not found.")
print("Please run the json.dump() sample code first.")
Execution Result:
Loaded settings from settings.json.
{'theme': 'dark', 'language': 'english', 'notifications': {'email': True, 'push': False}, 'version': '1.0.2'}
Current theme setting: dark
And with that, you've mastered all four basic magic spells! Use dumps/loads with the s for strings, and dump/load without the s for files. That's all there is to it!
[Copy-Paste & Run] Practice! Create a Dynamic Profile Card from JSON Data
Thanks for waiting! This is the climax of the article. Let's use everything we've learned so far to experience linking Python and JavaScript to dynamically generate HTML content from JSON data.
In a real-world development environment, data and display are separated in exactly this way. Once you experience this, you'll understand the true power of JSON!
The Complete, Ready-to-Run HTML Code
Copy all the code below, create a file named profile.html, and save it. Then, open that file in your web browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile Generated from JSON Data</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
background-color: #121212;
color: #e0e0e0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.card {
background-color: #1e1e1e;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.4);
padding: 2rem;
width: 320px;
border: 1px solid #333;
}
.card h1 {
color: #669df6;
margin-top: 0;
border-bottom: 2px solid #669df6;
padding-bottom: 0.5rem;
}
.card p {
line-height: 1.6;
}
.card .label {
font-weight: bold;
color: #8ab4f8;
}
.skills {
list-style: none;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.skills li {
background-color: #333;
padding: 0.3rem 0.8rem;
border-radius: 1rem;
font-size: 0.9em;
}
</style>
</head>
<body>
<!-- The profile card will be inserted here -->
<div id="profile-container"></div>
<!--
[This is Important!]
Normally, this JSON data comes from a server running Python.
In this sample, to simulate that behavior, we are embedding
the JSON data directly inside a <script> tag.
-->
<script id="user-json-data" type="application/json">
{
"name": "AI Assist Bot",
"age": 2,
"bio": "I'm an AI assistant who's great at Python and JavaScript. I'm here to give my all to support your web development!",
"is_active": true,
"skills": ["Data Analysis", "Web Development", "Natural Language Processing", "Debugging"]
}
</script>
<script>
// This JavaScript code runs in the browser
document.addEventListener('DOMContentLoaded', function() {
// 1. Get the JSON string from the <script> tag
var jsonScriptTag = document.getElementById('user-json-data');
var jsonString = jsonScriptTag.textContent;
// 2. Convert the JSON string into a JavaScript object
var userData = JSON.parse(jsonString);
// 3. Assemble the HTML content using the fetched data
var container = document.getElementById('profile-container');
// Generate the HTML for the skills list
var skillsHtml = userData.skills.map(function(skill) {
return '<li>' + skill + '</li>';
}).join('');
// Create the entire profile card HTML with string concatenation
var profileCardHtml =
'<div class="card">' +
'<h1>' + userData.name + '</h1>' +
'<p><span class="label">Age:</span> ' + userData.age + '</p>' +
'<p><span class="label">Bio:</span> ' + userData.bio + '</p>' +
'<p><span class="label">Status:</span> ' + (userData.is_active ? 'Active' : 'Inactive') + '</p>' +
'<h2 style="color: #669df6; font-size: 1.2em;">Skills</h2>' +
'<ul class="skills">' +
skillsHtml +
'</ul>' +
'</div>';
// 4. Insert the assembled HTML into the page
container.innerHTML = profileCardHtml;
});
</script>
</body>
</html>
When you open it in your browser, you should see a nicely styled profile card. And yet, you didn't write the card's elements directly in the HTML file!
In this code, the JavaScript below reads the JSON data written inside <script id="user-json-data">. The JSON.parse() function is the JavaScript version of Python's json.loads(). It then uses that data to dynamically build the HTML and insert it into the location with id="profile-container".
In actual web development, the Python server dynamically generates this JSON data portion and embeds it into an HTML template to send to the browser. You've just experienced the fundamental mechanism of how that works, all in a single file. Isn't that amazing?
Conclusion: JSON Isn't Scary, It's Your Ultimate Weapon!
This time, I've explained how to handle data using Python's json module and its importance in web development, mixed in with my own experiences.
- JSON is a common language used for data exchange between programs.
- Python has a standard
jsonmodule built-in. - For strings, use the ones with an `s`:
dumps/loads. - For files, use the ones without an `s`:
dump/load. - For non-ASCII characters, don't forget
ensure_ascii=False, and for readability,indent=4.
It might seem a bit unapproachable at first, but once you understand how JSON works, the range of websites you can create expands dramatically. The possibilities are endless, from integrating with external APIs to saving user-specific settings.
Please feel free to change the code in this article and experiment by asking, "What happens if I change this?" That process of trial and error is the best spice for your growth as a developer!
To the Next Step
Once you're comfortable handling data with JSON, let's learn how to receive information from external sources when you launch a program. Being able to handle command-line arguments will allow you to create even more powerful tools.