-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlistasdictjsonfile.py
More file actions
44 lines (36 loc) · 1.3 KB
/
listasdictjsonfile.py
File metadata and controls
44 lines (36 loc) · 1.3 KB
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
38
39
40
41
42
43
44
import json
import jsonfile
class ListAsDictJsonText(jsonfile.JsonText):
def __str__(self):
json_list = []
for item_id in sorted(self):
item = self[item_id]
item['id'] = item_id
json_list.append(item)
return json.dumps(json_list, ensure_ascii=False, indent='\t', sort_keys=True)
def read_list(self, json_list: list):
ids = set()
for item in json_list:
item_id = str(item.get('id', ''))
if item_id == '':
raise Exception(f'Missing id: {item}')
if not item_id.isnumeric():
raise Exception(f'Unexpected id: {item_id}')
if item_id in ids:
raise Exception(f'Duplicate id: {item_id}')
ids.add(item_id)
del ids
self.clear()
for item in json_list:
item_copy = item.copy()
item_id = item_copy.pop('id')
self[item_id] = item_copy
def read_text(self, text: str):
json_list = json.loads(text)
if not isinstance(json_list, list):
raise Exception('JSON list expected')
self.read_list(json_list)
class ListAsDictJsonFile(ListAsDictJsonText, jsonfile.JsonFile):
pass
class ListAsDictJsonGzip(ListAsDictJsonFile, jsonfile.JsonGzip):
pass