1 '''
2 JSONHelper
3
4 Various functions around JSON encoding/decoding
5
6 @author: Christian Holler (:decoder)
7
8 @license:
9
10 This Source Code Form is subject to the terms of the Mozilla Public
11 License, v. 2.0. If a copy of the MPL was not distributed with this
12 file, You can obtain one at http://mozilla.org/MPL/2.0/.
13
14 @contact: choller@mozilla.com
15 '''
16
18 '''
19 Retrieve a list from the given object using the given key
20
21 @type obj: map
22 @param obj: Source object
23
24 @type key: string
25 @param key: Key to retrieve from obj
26
27 @type mandatory: bool
28 @param mandatory: If True, throws an exception if the key is not found
29
30 @rtype: list
31 @return: List retrieved from object
32 '''
33 return __getTypeChecked(obj, key, [ list ], mandatory)
34
36 '''
37 Retrieve a string from the given object using the given key
38
39 @type obj: map
40 @param obj: Source object
41
42 @type key: string
43 @param key: Key to retrieve from obj
44
45 @type mandatory: bool
46 @param mandatory: If True, throws an exception if the key is not found
47
48 @rtype: string
49 @return: String retrieved from object
50 '''
51 return __getTypeChecked(obj, key, [ basestring ], mandatory)
52
54 '''
55 Retrieve an integer from the given object using the given key
56
57 @type obj: map
58 @param obj: Source object
59
60 @type key: string
61 @param key: Key to retrieve from obj
62
63 @type mandatory: bool
64 @param mandatory: If True, throws an exception if the key is not found
65
66 @rtype: long
67 @return: Number retrieved from object
68 '''
69 return __getTypeChecked(obj, key, [ int, long ], mandatory)
70
72 '''
73 Retrieve an object or string from the given object using the given key
74
75 @type obj: map
76 @param obj: Source object
77
78 @type key: string
79 @param key: Key to retrieve from obj
80
81 @type mandatory: bool
82 @param mandatory: If True, throws an exception if the key is not found
83
84 @rtype: string or dict
85 @return: String/Object object retrieved from object
86 '''
87 return __getTypeChecked(obj, key, [ basestring, dict ], mandatory)
88
90 '''
91 Retrieve a number or string from the given object using the given key
92
93 @type obj: map
94 @param obj: Source object
95
96 @type key: string
97 @param key: Key to retrieve from obj
98
99 @type mandatory: bool
100 @param mandatory: If True, throws an exception if the key is not found
101
102 @rtype: string or number
103 @return: String/Number object retrieved from object
104 '''
105 return __getTypeChecked(obj, key, [ basestring, long, int ], mandatory)
106
108 if not key in obj:
109 if mandatory:
110 raise RuntimeError('Expected key "%s" in object' % key)
111 return None
112
113 val = obj[key]
114
115 for valType in valTypes:
116 if isinstance(val, valType):
117 return val
118
119 raise RuntimeError('Expected any of types "%s" for key "%s" but got type %s' % (", ".join([str(i) for i in valTypes]), key, type(val)))
120