How To Use JSON in Python

Contents
In this article, you will learn how to use JSON in Python.
Using JSON in Python
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. In Python, you can use the json module to work with JSON data.
Here’s a quick guide to using JSON in Python:
Parsing JSON
You can parse JSON data using the json.loads() method, which takes a string as an argument and returns a Python object:
import json
json_string = '{"name": "John", "age": 30, "city": "New York"}'
python_object = json.loads(json_string)
print(python_object)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}
Encoding JSON
You can convert a Python object to a JSON string using the json.dumps() method:
import json
python_object = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(python_object)
print(json_string)
# Output: '{"name": "John", "age": 30, "city": "New York"}'
You can also specify additional parameters to control the format of the output JSON string:
import json
python_object = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(python_object, indent=4, sort_keys=True)
print(json_string)
# Output:
# {
# "age": 30,
# "city": "New York",
# "name": "John"
# }
Reading and Writing JSON from/to a file
You can also read and write JSON data from and to a file, respectively, using the json.load() and json.dump() methods.
Here’s an example of reading JSON from a file:
import json
with open('data.json', 'r') as file:
python_object = json.load(file)
print(python_object)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}
And here’s an example of writing JSON to a file:
import json
python_object = {
"name": "John",
"age": 30,
"city": "New York"
}
with open('data.json', 'w') as file:
json.dump(python_object, file)