JSON (JavaScript Object Notation) is a lightweight data interchange format. Python provides excellent support for working with JSON through its built-in json
module.
To start working with JSON in Python, you need to import the json
module:
import json
To parse JSON data in Python, use the json.loads()
function. It converts a JSON string into a Python object:
json_string = '{"name": "John", "age": 30, "city": "New York"}'
python_dict = json.loads(json_string)
print(python_dict['name']) # Output: John
To create JSON from Python objects, use the json.dumps()
function:
python_dict = {"name": "Alice", "age": 25, "city": "London"}
json_string = json.dumps(python_dict)
print(json_string) # Output: {"name": "Alice", "age": 25, "city": "London"}
Python's json module also provides functions to read from and write to JSON files:
with open('data.json', 'r') as file:
data = json.load(file)
data = {"name": "Bob", "age": 35, "city": "Paris"}
with open('output.json', 'w') as file:
json.dump(data, file)
For better readability, you can use the indent
parameter to format the JSON output:
formatted_json = json.dumps(data, indent=4)
print(formatted_json)
Python's json module can handle most built-in data types. However, for custom objects, you may need to implement a custom encoder:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
data = {"set": {1, 2, 3}}
json_string = json.dumps(data, cls=CustomEncoder)
print(json_string) # Output: {"set": [1, 2, 3]}
Python's json module provides a simple and efficient way to work with JSON data. By mastering these basic operations, you'll be well-equipped to handle JSON in your Python projects. For more advanced usage, explore popular JSON libraries that offer additional features and optimizations.