-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
44 lines (36 loc) · 1.21 KB
/
util.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
38
39
40
41
42
43
44
import json
from dataclasses import asdict, astuple, dataclass, fields
from typing import Any, List
# Dump list of dataclasses to full version and minimized version of JSON files
def dataclassToJson(objectClass: dataclass, objects: List[dataclass], filePrefix: str, sort = True) -> None:
try:
sort and objects.sort()
except TypeError: # '<' not supported between instances of 'objectClass' and 'objectClass'
print(f'Warning: {objectClass.__name__} is not sorted.')
json.dump(
[asdict(o) for o in objects],
open(f'{filePrefix}.json', 'w'),
indent=4
)
json.dump(
{
'keys': [f.name for f in fields(objectClass)],
'values': [astuple(o) for o in objects]
},
open(f'{filePrefix}.min.json', 'w'),
separators=(',', ':')
)
# Dump list of objects to full version and minimized version of JSON files
# Usually it's a list of strings
def listToJson(objects: List[Any], filePrefix: str) -> None:
objects.sort()
json.dump(
objects,
open(f'{filePrefix}.json', 'w'),
indent=4
)
json.dump(
objects,
open(f'{filePrefix}.min.json', 'w'),
separators=(',', ':')
)