forked from x4nth055/pythoncode-tutorials
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
Latest commit
28 lines (22 loc) · 757 Bytes
/
Copy pathexample.py
File metadata and controls
28 lines (22 loc) · 757 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
importrequests
importjson
# make API request and parse JSON automatically
data=requests.get("https://jsonplaceholder.typicode.com/users").json()
# save all data in a single JSON file
file_name="user_data.json"
withopen(file_name, "w") asf:
json.dump(data, f, indent=4)
print(file_name, "saved successfully!")
# or you can save each entry into a file
foruserindata:
# iterate over `data` list
file_name=f"user_{user['id']}.json"
withopen(file_name, "w") asf:
json.dump(user, f, indent=4)
print(file_name, "saved successfully!")
# load 2nd user for instance
file_name="user_2.json"
withopen(file_name) asf:
user_data=json.load(f)
print(user_data)
print("Username:", user_data["username"])