2 from osrf.net_obj import NetworkObject, parse_net_object
3 from osrf.const import OSRF_JSON_PAYLOAD_KEY, OSRF_JSON_CLASS_KEY
7 # if available, use the faster cjson module for encoding/decoding JSON
15 class NetworkEncoder(simplejson.JSONEncoder):
16 ''' Encoder used by simplejson '''
18 def default(self, obj):
20 Extend the default method offered by simplejson.JSONEncoder
22 Wraps the Python object into with OpenSRF class / payload keys
25 if isinstance(obj, NetworkObject):
26 reg = obj.get_registry()
29 # re-encode the object as an array if necessary
30 if reg.protocol == 'array':
33 objarray.append(data.get(key))
37 OSRF_JSON_CLASS_KEY: reg.hint,
38 OSRF_JSON_PAYLOAD_KEY: self.default(data)
43 def encode_object(obj):
44 ''' Generic opensrf object encoder, used by cjson '''
46 if isinstance(obj, dict):
48 for key, val in obj.iteritems():
49 newobj[key] = encode_object(val)
52 elif isinstance(obj, list):
53 return [encode_object(v) for v in obj]
55 elif isinstance(obj, NetworkObject):
56 reg = obj.get_registry()
59 if reg.protocol == 'array':
62 objarray.append(data.get(key))
66 OSRF_JSON_CLASS_KEY: reg.hint,
67 OSRF_JSON_PAYLOAD_KEY: encode_object(data)
75 """Turns a python object into a wrapped JSON object"""
77 return cjson.encode(encode_object(obj))
78 return simplejson.dumps(obj, cls=NetworkEncoder)
82 """Turns a JSON string into python objects"""
84 return parse_net_object(cjson.decode(json))
85 return parse_net_object(simplejson.loads(json))
87 def parse_json_raw(json):
88 """Parses JSON the old fashioned way."""
90 return cjson.decode(json)
91 return simplejson.loads(json)
94 """Stringifies an object as JSON with no additional logic."""
96 return cjson.encode(obj)
97 return simplejson.dumps(obj)
101 Returns a string of spaces-not-tabs for the desired indentation level
103 >>> print '"' + __tabs(0) + '"'
105 >>> print '"' + __tabs(4) + '"'
111 def debug_net_object(obj, depth=1):
112 """Returns a debug string for a given object.
114 If it's an NetworkObject and has registered keys, key/value pairs
115 are returned. Otherwise formatted JSON is returned"""
118 if isinstance(obj, NetworkObject):
119 reg = obj.get_registry()
120 keys = list(reg.keys) # clone it, so sorting won't break the original
127 key += '.' # pad the names to make the values line up somewhat
128 val = getattr(obj, k)()
130 subobj = val and not (isinstance(val, unicode) or isinstance(val, str) or \
131 isinstance(val, int) or isinstance(val, float) or isinstance(val, long))
133 debug_str += __tabs(depth) + key + ' = '
137 val = debug_net_object(val, depth+1)
139 debug_str += str(val)
145 osrf.log.log_internal("Pretty-printing NetworkObject")
146 debug_str = pprint(to_json(obj))
150 """JSON pretty-printer"""
160 if eatws and not _use_cjson: # simplejson adds a pesky space after array and object items
166 if (char == '{' or char == '[') and not instring:
168 result += char + '\n' + __tabs(tab)
171 if (char == '}' or char == ']') and not instring:
173 result += '\n' + __tabs(tab) + char
176 if char == ',' and not instring:
177 result += char + '\n' + __tabs(tab)
181 if char == ':' and not instring:
184 if char == '"' and not inescape:
185 instring = not instring
198 if __name__ == "__main__":