JSON (JavaScript Object Notation) is commonly used when working with APIs to exchange data between web applications and servers. It is lightweight, human-readable, and easy to parse.
In Python, working with JSON is straightforward, thanks to the built-in json module.
Ready to work with JSON in Python? Let's get started!
What is JSON?
JSON is a text-based format that represents structured data using key-value pairs. Here’s a simple JSON example taken from the response of one of our Network APIs:
{
"phoneNumber": "+99012345678",
"location": {
"latitude": 50.735851,
"longitude": 7.10066,
},
"is_active": true
}
JSON supports various data types:
Strings (e.g., "+99012345678")
Numbers (e.g., 25, 50.7358)
Booleans (true or false)
Null (null)
Objects (key-value pairs, similar to Python dictionaries)
Arrays (lists of values, similar to Python lists)
How to Work with JSON in Python
Python provides a built-in json module in its standard library, allowing developers to work with JSON data. You can import it using:
import json
Parse JSON Data
JSON data is usually converted into Python dictionaries. To parse and convert JSON data represented as a string, use json.loads()
json_data = '{"name": "Maria", "age": 25, "city": "Madrid"}' # string
parsed_data = json.loads(json_data) # Python dict
print(parsed_data["name"]) # prints “Maria”
json.loads() will be the method you’ll use to parse the JSON from the API responses.
Convert Python Objects to JSON
To convert (or serialize) Python objects into a JSON formatted string, use json.dumps()
python_dict = {"name": "John", "city": "London"}
json_string = json.dumps(python_dict)
print(json_string) # prints '{"name": "John", "city": "London"}'
You can also format the JSON output with indentation for readability:
formatted_json = json.dumps(python_dict, indent=4)
print(formatted_json)
Of course, invalid JSON formats will throw an exception. We must handle these errors using normal Python exception handling:
try:
invalid_json = '{"name": "John", "age": 30,}' # Incorrect JSON
parsed_data = json.loads(invalid_json)
except json.JSONDecodeError as e:
print("Error decoding JSON:", e)
Read and Write JSON Files
To write JSON data to a file, use json.dump():
with open("data.json", "w") as file:
json.dump(python_dict, file, indent=4)
To read JSON data from a file, use json.load():
with open("data.json", "r") as file:
data = json.load(file) # data is a Python dict
print(data)
Serialize Other Python Data Types to JSON
In the previous examples, we have seen how to serialize Python dictionaries. However, Python allows the serialization of other data types into JSON format:
Lists are naturally supported in JSON serialization:
list_data = ["one", "two", "three"]
json_list = json.dumps(list_data)
print(json_list) # ["one", "two", "three"]
Tuples can be converted into JSON lists:
tuple_data = ("one", "two", "three")
json_tuple = json.dumps(tuple_data)
print(json_tuple) # ["one", "two", "three"]
Python sets must be converted to lists before serialization:
set_data = {1, 2, 3, 4}
json_set = json.dumps(list(set_data))
print(json_set) # [1, 2, 3, 4]
Finally, to serialize custom objects, we must implement a custom encoder function:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def person_encoder(obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
raise TypeError("Object of type Person is not JSON serializable")
person = Person("Maria", 30)
json_person = json.dumps(person, default=person_encoder)
print(json_person) # {"name": "Alice", "age": 30}
Conclusion
Contrary to other formats (XML, we are looking at you!), working with JSON in Python is simple and efficient. We don’t need extra dependencies as the Python standard library includes the json package. Mastering JSON will help you improve your API integrations, especially when parsing API responses.
Got any questions or comments? Join our thriving Developer Community on Slack, follow us on X (formerly Twitter), or subscribe to our Developer Newsletter. Stay connected, share your progress, and keep up with the latest developer news, tips, and events!
)
Alvaro is a developer advocate at Vonage, focusing on Network APIs. Passionate about Developer Experience, APIs, and Open Source. Outside work, you can often find him exploring comic shops, attending sci-fi and horror festivals or crafting stuff with those renowned tiny plastic building blocks.