1 import simplejson, types
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
13 class NetworkEncoder(simplejson.JSONEncoder):
14 ''' Encoder used by simplejson '''
15 def default(self, obj):
17 if isinstance(obj, NetworkObject):
18 reg = obj.get_registry()
21 # re-encode the object as an array if necessary
22 if reg.protocol == 'array':
25 objarray.append(data.get(key))
29 OSRF_JSON_CLASS_KEY: reg.hint,
30 OSRF_JSON_PAYLOAD_KEY: self.default(data)
35 def encode_object(obj):
36 ''' Generic opensrf object encoder, used by cjson '''
38 if isinstance(obj, dict):
40 for k,v in obj.iteritems():
41 newobj[k] = encode_object(v)
44 elif isinstance(obj, list):
45 return [encode_object(v) for v in obj]
47 elif isinstance(obj, NetworkObject):
48 reg = obj.get_registry()
51 if reg.protocol == 'array':
54 objarray.append(data.get(key))
58 OSRF_JSON_CLASS_KEY: reg.hint,
59 OSRF_JSON_PAYLOAD_KEY: encode_object(data)
67 """Turns a python object into a wrapped JSON object"""
69 return cjson.encode(encode_object(obj))
70 return simplejson.dumps(obj, cls=NetworkEncoder)
74 """Turns a JSON string into python objects"""
76 return parse_net_object(cjson.decode(json))
77 return parse_net_object(simplejson.loads(json))
79 def parse_json_raw(json):
80 """Parses JSON the old fashioned way."""
82 return cjson.decode(json)
83 return simplejson.loads(json)
86 """Stringifies an object as JSON with no additional logic."""
88 return cjson.encode(json)
89 return simplejson.dumps(obj)
93 for i in range(depth):
97 def debug_net_object(obj, depth=1):
98 """Returns a debug string for a given object.
100 If it's an NetworkObject and has registered keys, key/value pairs
101 are returned. Otherwise formatted JSON is returned"""
104 if isinstance(obj, NetworkObject):
105 reg = obj.get_registry()
106 keys = list(reg.keys) # clone it, so sorting won't break the original
113 key += '.' # pad the names to make the values line up somewhat
114 val = getattr(obj, k)()
116 subobj = val and not (isinstance(val, unicode) or isinstance(val, str) or \
117 isinstance(val, int) or isinstance(val, float) or isinstance(val, long))
119 debug_str += __tabs(depth) + key + ' = '
123 val = debug_net_object(val, depth+1)
125 debug_str += str(val)
127 if not subobj: debug_str += '\n'
130 osrf.log.log_internal("Pretty-printing NetworkObject")
131 debug_str = pprint(to_json(obj))
135 """JSON pretty-printer"""
145 if eatws and not _use_cjson: # simpljson adds a pesky space after array and object items
151 if (c == '{' or c == '[') and not instring:
153 r += c + '\n' + __tabs(t)
156 if (c == '}' or c == ']') and not instring:
158 r += '\n' + __tabs(t) + c
161 if c == ',' and not instring:
162 r += c + '\n' + __tabs(t)
166 if c == ':' and not instring:
169 if c == '"' and not inescape:
170 instring = not instring