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
5 class NetworkEncoder(simplejson.JSONEncoder):
6 def default(self, obj):
8 if isinstance(obj, NetworkObject):
9 reg = obj.get_registry()
12 # re-encode the object as an array if necessary
13 if reg.protocol == 'array':
16 objarray.append(data.get(key))
20 OSRF_JSON_CLASS_KEY: reg.hint,
21 OSRF_JSON_PAYLOAD_KEY: self.default(data)
27 """Turns a python object into a wrapped JSON object"""
28 return simplejson.dumps(obj, cls=NetworkEncoder)
32 """Turns a JSON string into python objects"""
33 obj = simplejson.loads(json)
34 return parse_net_object(obj)
36 def parse_json_raw(json):
37 """Parses JSON the old fashioned way."""
38 return simplejson.loads(json)
41 """Stringifies an object as JSON with no additional logic."""
42 return simplejson.dumps(obj)
50 def debug_net_object(obj, depth=1):
51 """Returns a debug string for a given object.
53 If it's an NetworkObject and has registered keys, key/value pairs
54 are returned. Otherwise formatted JSON is returned"""
57 if isinstance(obj, NetworkObject):
58 reg = obj.get_registry()
59 keys = list(reg.keys) # clone it, so sorting won't break the original
65 while len(key) < 24: key += '.' # pad the names to make the values line up somewhat
66 val = getattr(obj, k)()
68 subobj = val and not (isinstance(val, unicode) or \
69 isinstance(val, int) or isinstance(val, float) or isinstance(val, long))
71 debug_str += __tabs(depth) + key + ' = '
75 val = debug_net_object(val, depth+1)
79 if not subobj: debug_str += '\n'
82 debug_str = pprint(to_json(obj))
86 """JSON pretty-printer"""
96 if eatws: # simpljson adds a pesky space after array and object items
102 if (c == '{' or c == '[') and not instring:
104 r += c + '\n' + __tabs(t)
107 if (c == '}' or c == ']') and not instring:
109 r += '\n' + __tabs(t) + c
112 if c == ',' and not instring:
113 r += c + '\n' + __tabs(t)
117 if c == ':' and not instring:
120 if c == '"' and not inescape:
121 instring = not instring