6.7 ג'סון, ובקשות פתרון
קובץ JSON¶
תחילה צרו את students.json:
[
{"name": "Amit", "age": 22, "average": 92},
{"name": "Dana", "age": 21, "average": 75},
{"name": "Yossi", "age": 23, "average": 88},
{"name": "Rina", "age": 22, "average": 61}
]
import json
from pathlib import Path
data = json.loads(Path("students.json").read_text())
for student in data:
if student["average"] > 80:
print(student["name"])
שמירה ל-JSON¶
import json
from pathlib import Path
shopping_list = {}
while True:
item = input("שם פריט (או 'סיום' לסיום): ")
if item == "סיום":
break
quantity = int(input("כמות: "))
shopping_list[item] = quantity
Path("shopping_list.json").write_text(json.dumps(shopping_list, ensure_ascii=False))
print("נשמר בהצלחה!")
בקשת GET¶
import requests
response = requests.get("https://jsonplaceholder.typicode.com/users")
users = response.json()
for user in users:
print(f"{user['name']} - {user['email']}")