Revision d357f531 lib/serializer.py

b/lib/serializer.py
36 36
except ImportError:
37 37
  import sha as sha1
38 38

  
39
# Check whether the simplejson module supports indentation
39

  
40 40
_JSON_INDENT = 2
41
try:
42
  simplejson.dumps(1, indent=_JSON_INDENT)
43
except TypeError:
44
  _JSON_INDENT = None
45 41

  
46 42
_RE_EOLSP = re.compile('[ \t]+$', re.MULTILINE)
47 43

  
48 44

  
45
def _GetJsonDumpers():
46
  """Returns two JSON functions to serialize data.
47

  
48
  @rtype: (callable, callable)
49
  @return: The function to generate a compact form of JSON and another one to
50
           generate a more readable, indented form of JSON (if supported)
51

  
52
  """
53
  plain_dump = simplejson.dumps
54

  
55
  # Check whether the simplejson module supports indentation
56
  try:
57
    simplejson.dumps(1, indent=_JSON_INDENT)
58
  except TypeError:
59
    # Indentation not supported
60
    indent_dump = plain_dump
61
  else:
62
    # Indentation supported
63
    indent_dump = lambda data: simplejson.dumps(data, indent=_JSON_INDENT)
64

  
65
  assert callable(plain_dump)
66
  assert callable(indent_dump)
67

  
68
  return (plain_dump, indent_dump)
69

  
70

  
71
(_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()
72

  
73

  
49 74
def DumpJson(data, indent=True):
50 75
  """Serialize a given object.
51 76

  
......
55 80
  @return: the string representation of data
56 81

  
57 82
  """
58
  if not indent or _JSON_INDENT is None:
59
    txt = simplejson.dumps(data)
83
  if indent:
84
    fn = _DumpJsonIndent
60 85
  else:
61
    txt = simplejson.dumps(data, indent=_JSON_INDENT, sort_keys=True)
86
    fn = _DumpJson
62 87

  
63
  txt = _RE_EOLSP.sub("", txt)
88
  txt = _RE_EOLSP.sub("", fn(data))
64 89
  if not txt.endswith('\n'):
65 90
    txt += '\n'
91

  
66 92
  return txt
67 93

  
68 94

  

Also available in: Unified diff