Page16/20
Working with JSON Β· Page 1 of 1
JSON for Data Science
Working with JSON
What is JSON?
JSON (JavaScript Object Notation) is the standard format for APIs and data exchange. Python's json module makes parsing trivial.
JSON Data Types Map to Python
| JSON | Python |
|---|---|
{...} | dict |
[...] | list |
"string" | str |
123 | int |
true/false | True/False |
null | None |
Parsing JSON (Strings β Python Objects)
import json
json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str) # loads = "load from string"
print(data["name"]) # Alice
Converting Python β JSON (Objects β Strings)
python_dict = {"status": "success", "code": 200}
json_str = json.dumps(python_dict) # dumps = "dump to string"
File Operations
# Read JSON from file
with open("data.json") as f:
data = json.load(f) # singular: load from file
# Write JSON to file
with open("output.json", "w") as f:
json.dump(data, f, indent=2) # pretty-print with indent
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦