JSON Module
What You'll Learn: In this tutorial, you'll discover how to work with JSON data in Python. JSON (JavaScript Object Notation) is a syntax for storing and exchanging data. Python has a built-in package called json that you can use to work with JSON data.
Importing the json Module
To work with JSON in Python, you need to import the json module.
Example Code:
import json
Parsing JSON - Convert from JSON to Python
If you have a JSON string, you can convert it to a Python dictionary using the json.loads() method.
Example Code:
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"]) # Output: 30
Converting from Python to JSON
If you have a Python object, you can convert it into a JSON string using the json.dumps() method.
Example Code:
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
Python Objects to JSON
You can convert Python objects of the following types into JSON strings: dict, list, tuple, string, int, float, True, False, None.
Example Code:
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Python to JSON Conversion Mapping
When you convert from Python to JSON, Python objects are converted into their JSON (JavaScript) equivalents.
Example Mapping:
dict→ Objectlist→ Arraytuple→ Arraystr→ Stringint→ Numberfloat→ NumberTrue→ trueFalse→ falseNone→ null
Example Code:
import json
x = {
"name": "John",
"age": 30,
"married": True,
"divorced": False,
"children": ("Ann","Billy"),
"pets": None,
"cars": [
{"model": "BMW 230", "mpg": 27.5},
{"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))
Formatting the JSON Result
You can make the JSON string more readable by using the indent parameter in the json.dumps() method.
Example Code:
json.dumps(x, indent=4)
You can also define custom separators using the separators parameter.
Example Code:
json.dumps(x, indent=4, separators=(". ", " = "))
Ordering the Result
You can sort the keys in the JSON output using the sort_keys parameter.
Example Code:
json.dumps(x, indent=4, sort_keys=True)
Try It Yourself: Fun Exercises
- Parse a JSON String:
- Create a JSON string representing a simple object, like a person's details, and convert it to a Python dictionary.
- Convert a Python Object to JSON:
- Write a Python dictionary and convert it to a JSON string, then print the result.
- Format JSON Output:
- Use the
json.dumps()method to format a JSON string with indentation and custom separators.
- Use the
Summary:
In this Python tutorial, we learned how to work with JSON data using the json module. We explored how to convert JSON strings to Python dictionaries and vice versa, as well as how to format and sort JSON output. Keep experimenting and have fun with Python!