Python JSON Tutorial: Parse, Convert, and Format JSON in Python

Python JSON Tutorial: Parse, Convert, and Format JSON in Python

JSON (JavaScript Object Notation) is one of the most popular formats for exchanging data. It is lightweight, text-based, and widely supported across programming languages. In Python, the json module allows you to parse JSON strings, convert Python objects to JSON, format the results, and even order them. In this tutorial, we will cover what JSON is, how to use JSON in Python, syntax, examples, FAQs, and exercises to help you master JSON step by step.


🔹 What is JSON?

JSON is a text-based format that represents structured data. It looks similar to Python dictionaries but follows a universal format used in APIs, databases, and configuration files.

Feature JSON Python Equivalent
Object{}dict
Array[]list / tuple
String"text"str
Number123, 45.6int, float
Booleantrue / falseTrue / False
NullnullNone

🔹 Python Objects That Can Be Converted to JSON

Python provides the json.dumps() method to convert Python objects into JSON strings. The following Python objects can be converted:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None

🔹 Parse JSON - Convert from JSON to Python

We use json.loads() to parse JSON strings and convert them into Python dictionaries.

import json

# JSON string
data = '{"name": "Alice", "age": 25, "city": "New York"}'

# Parse JSON into Python dictionary
parsed = json.loads(data)

print(parsed["name"])  # Output: Alice

🔹 Convert from Python to JSON

We use json.dumps() to convert Python objects into JSON strings.

import json

# Python dictionary
person = {"name": "Bob", "age": 30, "city": "London"}

# Convert dictionary to JSON string
result = json.dumps(person)

print(result)

🔹 Format the Result

JSON output can be formatted using the indent parameter to make it more readable.

result = json.dumps(person, indent=4)
print(result)
Output:
{
    "name": "Bob",
    "age": 30,
    "city": "London"
}

🔹 Order the Result

To sort keys alphabetically in JSON, use sort_keys=True.

result = json.dumps(person, indent=4, sort_keys=True)
print(result)
Output:
{
    "age": 30,
    "city": "London",
    "name": "Bob"
}

🔹 Real-World Example

JSON is commonly used in APIs. For example, a weather API might return JSON data that can be parsed easily in Python.

import json

weather_data = '{"temperature": 28, "humidity": 65, "city": "Miami"}'
parsed = json.loads(weather_data)

print(f"City: {parsed['city']}, Temp: {parsed['temperature']}°C")

🔹 Exercises

📝 Click to view Exercises
  1. Create a Python program that converts a dictionary of student marks into a JSON string.
  2. Write a script to parse JSON data about books and print the book titles.
  3. Experiment with indent and sort_keys parameters in json.dumps().
  4. Parse a JSON string of employee data and print only the names of employees above age 25.
  5. Save a Python dictionary to a JSON file and load it back into Python.

🔹 FAQs

1. What is the difference between json.load() and json.loads()?

json.load() reads JSON from a file, while json.loads() parses JSON from a string.

2. Can JSON handle tuples?

Yes, but tuples are converted into lists because JSON does not support tuples.

3. Is JSON language-independent?

Yes ✅ JSON is supported by most programming languages including Python, Java, JavaScript, C#, and more.

4. Why use JSON over XML?

JSON is lightweight, faster, and easier to parse compared to XML, making it the preferred choice for APIs and web apps.

5. Which Python module is used for JSON?

Python has a built-in json module for encoding and decoding JSON data.


🔹 Tips & Tricks

  • Always use indent when debugging JSON to make output readable.
  • Use sort_keys=True to keep JSON outputs consistent.
  • When working with files, use json.dump() (write) and json.load() (read).
  • Remember that tuples become lists in JSON conversion.
  • Validate JSON data before parsing to avoid errors.

🔹 Conclusion

JSON is a vital part of modern programming and data handling. With Python’s json module, you can parse JSON strings, convert Python objects to JSON, format the results, and order keys for consistency. Understanding JSON is essential if you want to work with APIs, web applications, or structured data in Python. Keep practicing with the exercises to strengthen your understanding.


👉 Related Reads

Explore more beginner-friendly topics and practice materials in our Programming Resource Hub.

Post a Comment

0 Comments