-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path2-export_to_JSON.py
executable file
·37 lines (33 loc) · 1.13 KB
/
2-export_to_JSON.py
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
29
30
31
32
33
34
35
36
37
#!/usr/bin/python3
"""
Using https://jsonplaceholder.typicode.com
gathers data from API and exports it to JSON file
Implemented using recursion
"""
import json
import re
import requests
import sys
API = "https://jsonplaceholder.typicode.com"
"""REST API url"""
if __name__ == '__main__':
if len(sys.argv) > 1:
if re.fullmatch(r'\d+', sys.argv[1]):
id = int(sys.argv[1])
user_res = requests.get('{}/users/{}'.format(API, id)).json()
todos_res = requests.get('{}/todos'.format(API)).json()
user_name = user_res.get('username')
todos = list(filter(lambda x: x.get('userId') == id, todos_res))
with open("{}.json".format(id), 'w') as json_file:
user_data = list(map(
lambda x: {
"task": x.get("title"),
"completed": x.get("completed"),
"username": user_name
},
todos
))
user_data = {
"{}".format(id): user_data
}
json.dump(user_data, json_file)