-
Notifications
You must be signed in to change notification settings - Fork 5
/
jsonutil.py
84 lines (58 loc) · 2.61 KB
/
jsonutil.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#######################################################################
# Copyright (c) 2019 Alejandro Pereira
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>
#######################################################################
#!/usr/bin/python
import jsonpickle
#region Module Functions
__jsonPyObjectAcceptedPrefixes = None
def initialize(acceptedPrefixes):
if not acceptedPrefixes: return
global __jsonPyObjectAcceptedPrefixes
__jsonPyObjectAcceptedPrefixes = acceptedPrefixes
def encodeJson(value):
jsonValue = jsonpickle.encode(value)
return jsonValue
def decodeJson(jsonValue):
if not jsonValue: return None
__sanitize(jsonValue)
value = jsonpickle.decode(jsonValue)
return value
def serializeJson(value, fileName):
jsonFile = open(fileName, 'w')
jsonValue = encodeJson(value)
jsonFile.write(jsonValue)
jsonFile.close()
def deserializeJson(fileName):
jsonFile = open(fileName)
jsonValue = jsonFile.read()
value = decodeJson(jsonValue)
return value
def __sanitize(value):
"""Ensures the specified value contains safe JSON."""
if not value: return
# Allow "py/object" only. Do not allow "py/type" or "py/reduce".
if 'py/reduce' in value or 'py/type' in value:
raise ValueError('py/reduce and py/type are not allowed in JSON values to be decoded.')
# Get the list of "py/object" values. Accept only the ones with the accepted prefix.
global __jsonPyObjectAcceptedPrefixes
if not __jsonPyObjectAcceptedPrefixes or len(__jsonPyObjectAcceptedPrefixes) == 0: return
pattern = '"py/object"[ \t]*:[ \t]*"[^"]+"'
matches = re.findall(pattern, value, re.DOTALL)
if matches and len(matches):
for match in matches:
pair = match.split(":")
typeName = pair[1].strip(' \t"')
accepted = [ item for item in __jsonPyObjectAcceptedPrefixes if typeName.startswith(item) ]
if not (accepted and len(accepted)):
raise ValueError('Specified type name is not allowed for decoding.')
#endregion