Statistics
| Branch: | Tag: | Revision:

root / lib / serializer.py @ 742f39ac

History | View | Annotate | Download (1.5 kB)

1 8d14b30d Iustin Pop
#
2 8d14b30d Iustin Pop
#
3 8d14b30d Iustin Pop
4 8d14b30d Iustin Pop
# Copyright (C) 2007, 2008 Google Inc.
5 8d14b30d Iustin Pop
#
6 8d14b30d Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 8d14b30d Iustin Pop
# it under the terms of the GNU General Public License as published by
8 8d14b30d Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 8d14b30d Iustin Pop
# (at your option) any later version.
10 8d14b30d Iustin Pop
#
11 8d14b30d Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 8d14b30d Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 8d14b30d Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 8d14b30d Iustin Pop
# General Public License for more details.
15 8d14b30d Iustin Pop
#
16 8d14b30d Iustin Pop
# You should have received a copy of the GNU General Public License
17 8d14b30d Iustin Pop
# along with this program; if not, write to the Free Software
18 8d14b30d Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 8d14b30d Iustin Pop
# 02110-1301, USA.
20 8d14b30d Iustin Pop
21 8d14b30d Iustin Pop
"""Serializer abstraction module
22 8d14b30d Iustin Pop

23 8d14b30d Iustin Pop
This module introduces a simple abstraction over the serialization
24 8d14b30d Iustin Pop
backend (currently json).
25 8d14b30d Iustin Pop

26 8d14b30d Iustin Pop
"""
27 8d14b30d Iustin Pop
28 8d14b30d Iustin Pop
import simplejson
29 8d14b30d Iustin Pop
import ConfigParser
30 8d14b30d Iustin Pop
import re
31 8d14b30d Iustin Pop
32 8d14b30d Iustin Pop
# Check whether the simplejson module supports indentation
33 8d14b30d Iustin Pop
_JSON_INDENT = 2
34 8d14b30d Iustin Pop
try:
35 8d14b30d Iustin Pop
  simplejson.dumps(1, indent=_JSON_INDENT)
36 8d14b30d Iustin Pop
except TypeError:
37 8d14b30d Iustin Pop
  _JSON_INDENT = None
38 8d14b30d Iustin Pop
39 8d14b30d Iustin Pop
_RE_EOLSP = re.compile('\s+$', re.MULTILINE)
40 8d14b30d Iustin Pop
41 8d14b30d Iustin Pop
42 8d14b30d Iustin Pop
def Dump(data):
43 8d14b30d Iustin Pop
  """Serialize a given object.
44 8d14b30d Iustin Pop

45 8d14b30d Iustin Pop
  """
46 8d14b30d Iustin Pop
  if _JSON_INDENT is None:
47 8d14b30d Iustin Pop
    txt = simplejson.dumps(data)
48 8d14b30d Iustin Pop
  else:
49 8d14b30d Iustin Pop
    txt = simplejson.dumps(data, indent=_JSON_INDENT)
50 8d14b30d Iustin Pop
  if not txt.endswith('\n'):
51 8d14b30d Iustin Pop
    txt += '\n'
52 8d14b30d Iustin Pop
  txt = _RE_EOLSP.sub("", txt)
53 8d14b30d Iustin Pop
  return txt
54 8d14b30d Iustin Pop
55 8d14b30d Iustin Pop
56 8d14b30d Iustin Pop
def Load(txt):
57 8d14b30d Iustin Pop
  """Unserialize data from a string.
58 8d14b30d Iustin Pop

59 8d14b30d Iustin Pop
  """
60 8d14b30d Iustin Pop
  return simplejson.loads(txt)