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
6 class NetworkEncoder(simplejson.JSONEncoder):
7 def default(self, obj):
9 if isinstance(obj, NetworkObject):
10 reg = obj.get_registry()
13 # re-encode the object as an array if necessary
14 if reg.protocol == 'array':
17 objarray.append(data.get(key))
21 OSRF_JSON_CLASS_KEY: reg.hint,
22 OSRF_JSON_PAYLOAD_KEY: self.default(data)
28 """Turns a python object into a wrapped JSON object"""
29 return simplejson.dumps(obj, cls=NetworkEncoder)
33 """Turns a JSON string into python objects"""
34 obj = simplejson.loads(json)
35 return parse_net_object(obj)
37 def parse_json_raw(json):
38 """Parses JSON the old fashioned way."""
39 return simplejson.loads(json)
42 """Stringifies an object as JSON with no additional logic."""
43 return simplejson.dumps(obj)
47 for i in range(depth):
51 def debug_net_object(obj, depth=1):
52 """Returns a debug string for a given object.
54 If it's an NetworkObject and has registered keys, key/value pairs
55 are returned. Otherwise formatted JSON is returned"""
58 if isinstance(obj, NetworkObject):
59 osrf.log.log_internal("Returning key/value pairs for NetworkObject")
60 reg = obj.get_registry()
61 keys = list(reg.keys) # clone it, so sorting won't break the original
68 key += '.' # pad the names to make the values line up somewhat
69 val = getattr(obj, k)()
71 subobj = val and not (isinstance(val, unicode) or \
72 isinstance(val, int) or isinstance(val, float) or isinstance(val, long))
74 debug_str += __tabs(depth) + key + ' = '
77 osrf.log.log_internal("Returning key/value pairs for subobject")
79 val = debug_net_object(val, depth+1)
83 if not subobj: debug_str += '\n'
86 osrf.log.log_internal("Pretty-printing NetworkObject")
87 debug_str = pprint(to_json(obj))
91 """JSON pretty-printer"""
101 if eatws: # simpljson adds a pesky space after array and object items
107 if (c == '{' or c == '[') and not instring:
109 r += c + '\n' + __tabs(t)
112 if (c == '}' or c == ']') and not instring:
114 r += '\n' + __tabs(t) + c
117 if c == ',' and not instring:
118 r += c + '\n' + __tabs(t)
122 if c == ':' and not instring:
125 if c == '"' and not inescape:
126 instring = not instring