JSON (JavaScript Object Notation) is a lightweight text format for storing and exchanging data. It is language-independent but uses syntax similar to JavaScript objects. In Python, we use the built-in json module to convert between Python objects and JSON strings, and to read/write JSON files.
None map naturally to JSON objects, arrays, strings, numbers, booleans and null.json.dumps() / json.dump() – convert Python objects to JSON (string or file).json.loads() / json.load() – parse JSON (string or file) into Python objects."like this".{"key": "value"}[1, 2, 3]nulldumps() or dump().loads() or load().Use json.dumps() to convert a Python object into a JSON-formatted string that you can print, send over a network, or store in a database.
import json
person = {"name": "Alice", "age": 25, "city": "New York"}
json_data = json.dumps(person)
print(json_data)
# {"name": "Alice", "age": 25, "city": "New York"}
Use json.loads() to parse a JSON string and get back a Python object (usually a dictionary or list).
import json
json_string = '{"name": "Bob", "age": 30, "city": "London"}'
person = json.loads(json_string)
print(person["name"]) # Bob
Use json.dump() and json.load() to write JSON to a file and read JSON from a file.
import json
# Write JSON to file
data = {"brand": "Ford", "model": "Mustang", "year": 1964}
with open("car.json", "w") as file:
json.dump(data, file)
# Read JSON from file
with open("car.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data)
Use the indent and sort_keys arguments of json.dumps() to produce human-readable (pretty-printed) JSON.
import json
# A simple Python dictionary
person = {"name": "Charlie", "age": 28, "city": "Berlin"}
# Pretty-print JSON with indentation and sorted keys
print(json.dumps(person, indent=4, sort_keys=True))
json.dumps(person) returns a string like {"name": "Alice", "age": 25, "city": "New York"}.json.loads(json_string), you can access values using dictionary syntax, e.g. person["name"].json.dump(data, file) writes JSON text into car.json, and json.load(file) reads it back as a Python dictionary.indent=4 prints JSON on multiple lines, and sort_keys=True orders keys alphabetically for easier reading.json.dumps() for converting Python objects to a JSON string.json.dump() when you want to write JSON directly to a file object.json.loads() to parse JSON strings into Python objects.json.load() to parse JSON from an open file.indent and sort_keys to make JSON output more human-readable.json.dumps().json.loads().indent values (2, 4, 8) and see how the printed JSON changes.