-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy path_json.py
61 lines (44 loc) · 1.37 KB
/
_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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from enum import Enum
from typing import AnyStr, Any
import os
AZUREFUNCTIONS_UJSON_ENV_VAR = 'AZUREFUNCTIONS_UJSON'
try:
import ujson
if AZUREFUNCTIONS_UJSON_ENV_VAR in os.environ:
HAS_UJSON = bool(os.environ[AZUREFUNCTIONS_UJSON_ENV_VAR])
else:
HAS_UJSON = True
import json
except ImportError:
import json
HAS_UJSON = False
class StringifyEnum(Enum):
"""This class output name of enum object when printed as string."""
def __str__(self):
return str(self.name)
def __json__(self):
"""For ujson encoding."""
return f'"{self.name}"'
class StringifyEnumJsonEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, StringifyEnum):
return str(o)
return super().default(o)
JSONDecodeError = json.JSONDecodeError
if HAS_UJSON:
def dumps(v: Any, **kwargs) -> str:
if 'default' in kwargs:
return json.dumps(v, **kwargs)
if 'cls' in kwargs:
del kwargs['cls']
return ujson.dumps(v, **kwargs)
def loads(s: AnyStr, **kwargs):
if kwargs:
return json.loads(s, **kwargs)
else: # ujson takes no kwargs
return ujson.loads(s)
else:
dumps = json.dumps # type: ignore
loads = json.loads