Python JSON
JSON is a format for saving data and passing it between systems.
It is plain text that uses a simple object notation.
JSON in Python
Python ships with a built-in package named json for handling JSON data.
Example
import json
Parse JSON - Convert from JSON to Python
A JSON string can be parsed with the json.loads() method.
In this example, what comes back is a Python dictionary.
Example
json.loads().
The JSON string contains name, age, and city. Print the age value.
Output: complete Python program
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"])
Convert from Python to JSON
Going the other way, the json.dumps() method turns a Python object into a JSON string.
These Python types can be converted into JSON strings:
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
During the conversion, each Python object becomes its JSON equivalent:
- dict → Object
- list → Array
- tuple → Array
- str → String
- int → Number
- float → Number
- True → true
- False → false
- None → null
Example
json.dumps().
Print the resulting JSON string.
Output: complete Python program
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)
Example
json.dumps() for each and print the results.
Output: complete Python program
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))
Example
json.dumps().
Output: complete Python program
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))
Format the Result
The JSON string printed above is hard on the eyes, because it has no indentation or line breaks.
json.dumps() takes parameters that make the output more readable:
The separators can be customized too. Their default is (", ", ": "): a comma and a space between objects, and a colon and a space between keys and values:
Example
indent parameter to choose how many spaces each level is indented:json.dumps() with the indent parameter set to 4 to format JSON output with indentation.
Output: complete Python program
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, indent=4))
Example
separators parameter:json.dumps() with indent=4 and custom separators=(". ", " = ") to change the default separator.
Output: complete Python program
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, indent=4, separators=(". ", " = ")))
Order the Result
Other parameters of json.dumps() control the order of the keys in the output:
Example
sort_keys parameter to choose whether the output gets sorted:json.dumps() with indent=4 and sort_keys=True to sort the keys in JSON output.
Output: complete Python program
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, indent=4, sort_keys=True))