Working with JSON in Python: A Complete Guide

Working with JSON in Python: A Complete Guide

JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It is easy for humans to read and write, and easy for machines to parse and generate. Python provides a built-in package called json to work with JSON data efficiently.

Importing the JSON Module

To get started, you need to import the json module:

import json

Parsing JSON: Convert from JSON to Python

If you have a JSON string, you can parse it into a Python dictionary using the json.loads() method.

Example: Parsing JSON

x = '{ "name": "Alice", "age": 28, "city": "Paris" }'
y = json.loads(x)
print(y["city"])

Converting Python to JSON

You can also convert a Python object (like a dictionary) into a JSON string using the json.dumps() method.

Example: Converting Python to JSON

person = {"name": "Alice", "age": 28, "city": "Paris"}
json_string = json.dumps(person)
print(json_string)

Supported Data Types

You can convert various Python data types into JSON strings, including:

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

Example: Converting Multiple Data Types

print(json.dumps({"name": "Alice", "age": 28}))
print(json.dumps(["apple", "banana"]))
print(json.dumps(("apple", "banana")))
print(json.dumps(3.14))
print(json.dumps(True))

Formatting the Result

The json.dumps() method allows for formatting the output to make it more readable. You can set the indent parameter for indentation.

Example: Using Indentation

formatted_json = json.dumps(person, indent=4)
print(formatted_json)

Customizing Separators

You can also customize the separators used in the JSON output.

Example: Custom Separators

json_string = json.dumps(person, indent=4, separators=(", ", " = "))
print(json_string)

Sorting the Output

The json.dumps() method has a sort_keys parameter to sort the keys in the output.

Example: Sorting Keys

sorted_json = json.dumps(person, indent=4, sort_keys=True)
print(sorted_json)

Exercise

When you parse JSON using the json.loads() method, what type of Python data structure is returned?

  • list
  • set
  • tuple
  • dictionary

Conclusion

In this guide, we explored how to work with JSON in Python using the built-in json module. We learned how to parse JSON strings into Python dictionaries, convert Python objects into JSON strings, and format the output for better readability. Understanding JSON handling in Python is essential for effective data exchange and manipulation in programming.