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)
45 if isinstance(obj, list):
46 return [encode_object(v) for v in obj]
49 if isinstance(obj, NetworkObject):
50 reg = obj.get_registry()
52 if reg.protocol == 'array':
55 objarray.append(data.get(key))
59 OSRF_JSON_CLASS_KEY: reg.hint,
60 OSRF_JSON_PAYLOAD_KEY: encode_object(data)
68 """Turns a python object into a wrapped JSON object"""
70 return cjson.encode(encode_object(obj))
71 return simplejson.dumps(obj, cls=NetworkEncoder)
75 """Turns a JSON string into python objects"""
77 return parse_net_object(cjson.decode(json))
78 return parse_net_object(simplejson.loads(json))
80 def parse_json_raw(json):
81 """Parses JSON the old fashioned way."""
83 return cjson.decode(json)
84 return simplejson.loads(json)
87 """Stringifies an object as JSON with no additional logic."""
89 return cjson.encode(json)
90 return simplejson.dumps(obj)
94 for i in range(depth):
98 def debug_net_object(obj, depth=1):
99 """Returns a debug string for a given object.
101 If it's an NetworkObject and has registered keys, key/value pairs
102 are returned. Otherwise formatted JSON is returned"""
105 if isinstance(obj, NetworkObject):
106 reg = obj.get_registry()
107 keys = list(reg.keys) # clone it, so sorting won't break the original
114 key += '.' # pad the names to make the values line up somewhat
115 val = getattr(obj, k)()
117 subobj = val and not (isinstance(val, unicode) or isinstance(val, str) or \
118 isinstance(val, int) or isinstance(val, float) or isinstance(val, long))
120 debug_str += __tabs(depth) + key + ' = '
124 val = debug_net_object(val, depth+1)
126 debug_str += str(val)
128 if not subobj: debug_str += '\n'
131 osrf.log.log_internal("Pretty-printing NetworkObject")
132 debug_str = pprint(to_json(obj))
136 """JSON pretty-printer"""
146 if eatws and not _use_cjson: # simpljson adds a pesky space after array and object items
152 if (c == '{' or c == '[') and not instring:
154 r += c + '\n' + __tabs(t)
157 if (c == '}' or c == ']') and not instring:
159 r += '\n' + __tabs(t) + c
162 if c == ',' and not instring:
163 r += c + '\n' + __tabs(t)
167 if c == ':' and not instring:
170 if c == '"' and not inescape:
171 instring = not instring