1 import simplejson, types
2 from osrf.net_obj import *
3 from osrf.const import OSRF_JSON_PAYLOAD_KEY, OSRF_JSON_CLASS_KEY
5 class osrfJSONNetworkEncoder(simplejson.JSONEncoder):
6 def default(self, obj):
8 if isinstance(obj, osrfNetworkObject):
9 reg = obj.getRegistry()
12 # re-encode the object as an array if necessary
13 if reg.wireProtocol == 'array':
20 OSRF_JSON_CLASS_KEY: reg.hint,
21 OSRF_JSON_PAYLOAD_KEY: self.default(data)
26 def osrfObjectToJSON(obj):
27 """Turns a python object into a wrapped JSON object"""
28 return simplejson.dumps(obj, cls=osrfJSONNetworkEncoder)
31 def osrfJSONToObject(json):
32 """Turns a JSON string into python objects"""
33 obj = simplejson.loads(json)
34 return parseNetObject(obj)
36 def osrfParseJSONRaw(json):
37 """Parses JSON the old fashioned way."""
38 return simplejson.loads(json)
40 def osrfToJSONRaw(obj):
41 """Stringifies an object as JSON with no additional logic."""
42 return simplejson.dumps(obj)
46 for i in range(t): r += ' '
49 def osrfDebugNetworkObject(obj, t=1):
50 """Returns a debug string for a given object.
52 If it's an osrfNetworkObject and has registered keys, key/value p
53 pairs are returned. Otherwise formatted JSON is returned"""
56 if isinstance(obj, osrfNetworkObject):
57 reg = obj.getRegistry()
58 keys = list(reg.keys) # clone it, so sorting won't break the original
64 while len(key) < 24: key += '.' # pad the names to make the values line up somewhat
65 val = getattr(obj, k)()
67 subobj = val and not (isinstance(val,unicode) or \
68 isinstance(val, int) or isinstance(val, float) or isinstance(val, long))
70 s += __tabs(t) + key + ' = '
74 val = osrfDebugNetworkObject(val, t+1)
78 if not subobj: s += '\n'
81 s = osrfFormatJSON(osrfObjectToJSON(obj))
84 def osrfFormatJSON(json):
85 """JSON pretty-printer"""
95 if eatws: # simpljson adds a pesky space after array and object items
101 if (c == '{' or c == '[') and not instring:
103 r += c + '\n' + __tabs(t)
106 if (c == '}' or c == ']') and not instring:
108 r += '\n' + __tabs(t) + c
111 if c == ',' and not instring:
112 r += c + '\n' + __tabs(t)
116 if c == ':' and not instring:
119 if c == '"' and not inescape:
120 instring = not instring