Labs ICT
โญ Pro Login

JSON

JSON dumps() and loads()

json.dumps() converts a Python object to a JSON string. json.loads() parses a JSON string back into a Python object.

import json

data = {"name": "Alice", "age": 30, "skills": ["Python", "SQL"]}
json_str = json.dumps(data, indent=2)
print(json_str)

parsed = json.loads(json_str)
print(parsed["name"])
Try it Yourself โ†’

Reading and Writing JSON Files

Use json.dump() to write directly to a file and json.load() to read one. The file must be opened in text mode.

import json

data = {"users": [{"id": 1, "name": "Bob"}, {"id": 2, "name": "Jane"}]}

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json", "r") as f:
    loaded = json.load(f)

print(loaded)
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which method converts a Python object to a JSON string?