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):
7 if isinstance(obj, osrfNetworkObject):
9 OSRF_JSON_CLASS_KEY: obj.getRegistry().hint,
10 OSRF_JSON_PAYLOAD_KEY: self.default(obj.getData())
15 def osrfObjectToJSON(obj):
16 """Turns a python object into a wrapped JSON object"""
17 return simplejson.dumps(obj, cls=osrfJSONNetworkEncoder)
20 def osrfJSONToObject(json):
21 """Turns a JSON string into python objects"""
22 obj = simplejson.loads(json)
23 return parseNetObject(obj)
25 def osrfParseJSONRaw(json):
26 """Parses JSON the old fashioned way."""
27 return simplejson.loads(json)
29 def osrfToJSONRaw(obj):
30 """Stringifies an object as JSON with no additional logic."""
31 return simplejson.dumps(obj)
35 for i in range(t): r += ' '
38 def osrfDebugNetworkObject(obj, t=1):
39 """Returns a debug string for a given object.
41 If it's an osrfNetworkObject and has registered keys, key/value p
42 pairs are returned. Otherwise formatted JSON is returned"""
45 if isinstance(obj, osrfNetworkObject):
46 reg = obj.getRegistry()
47 keys = list(reg.keys) # clone it, so sorting won't break the original
53 while len(key) < 24: key += '.' # pad the names to make the values line up somewhat
54 val = getattr(obj, k)()
56 subobj = val and not (isinstance(val,unicode) or \
57 isinstance(val, int) or isinstance(val, float) or isinstance(val, long))
59 s += __tabs(t) + key + ' = '
63 val = osrfDebugNetworkObject(val, t+1)
67 if not subobj: s += '\n'
70 s = osrfFormatJSON(osrfObjectToJSON(obj))
73 def osrfFormatJSON(json):
74 """JSON pretty-printer"""
84 if (c == '{' or c == '[') and not instring:
86 r += c + '\n' + __tabs(t)
89 if (c == '}' or c == ']') and not instring:
91 r += '\n' + __tabs(t) + c
94 if c == ',' and not instring:
95 r += c + '\n' + __tabs(t)
98 if c == '"' and not inescape:
99 instring = not instring