1
# -*- coding: utf-8 -*-
6
This module implements a simple JavaScript serializer.
7
Uses the basestring encode function from simplejson by Bob Ippolito.
9
:copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS.
10
:license: BSD, see LICENSE for details.
15
_str_re = re.compile(r'"(\\\\|\\"|[^"])*"')
16
_int_re = re.compile(r'\d+')
17
_name_re = re.compile(r'[a-zA-Z]\w*')
18
_nameonly_re = re.compile(r'[a-zA-Z]\w*$')
20
# escape \, ", control characters and everything outside ASCII
21
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
32
ESCAPED = re.compile(r'\\u.{4}|\\.')
43
return '\\u%04x' % (n,)
47
s1 = 0xd800 | ((n >> 10) & 0x3ff)
48
s2 = 0xdc00 | (n & 0x3ff)
49
return '\\u%04x\\u%04x' % (s1, s2)
50
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
53
return ESCAPED.sub(lambda m: eval('u"'+m.group()+'"'), s)
57
abstract else instanceof switch
58
boolean enum int synchronized
59
break export interface this
60
byte extends long throw
61
case false native throws
62
catch final new transient
63
char finally null true
64
class float package try
65
const for private typeof
66
continue function protected var
67
debugger goto public void
68
default if return volatile
69
delete implements short while
71
double in super""".split())
73
def dumps(obj, key=False):
75
if not isinstance(obj, basestring):
77
if _nameonly_re.match(obj) and obj not in reswords:
78
return obj # return it as a bare word
80
return encode_string(obj)
83
elif obj is True or obj is False:
84
return obj and 'true' or 'false'
85
elif isinstance(obj, (int, long, float)):
87
elif isinstance(obj, dict):
88
return '{%s}' % ','.join('%s:%s' % (
91
) for key, value in obj.iteritems())
92
elif isinstance(obj, (tuple, list, set)):
93
return '[%s]' % ','.join(dumps(x) for x in obj)
94
elif isinstance(obj, basestring):
95
return encode_string(obj)
96
raise TypeError(type(obj))
103
"""Loader that can read the JS subset the indexer produces."""
127
if keys[-1] is not nothing:
128
raise ValueError("unfinished dict")
135
if isinstance(obj, dict):
136
if keys[-1] is nothing:
137
raise ValueError("invalid key object", oldobj)
138
obj[keys[-1]] = oldobj
146
raise ValueError("multiple keys")
147
if isinstance(obj, dict):
151
if not isinstance(obj, dict):
152
raise ValueError("colon in list")
155
raise ValueError("multiple values")
158
m = _str_re.match(x, i)
160
y = decode_string(m.group()[1:-1])
162
m = _int_re.match(x, i)
166
m = _name_re.match(x, i)
176
raise ValueError("bareword as value")
178
raise ValueError("read error at pos %d" % i)
180
if isinstance(obj, dict):
189
raise ValueError("nothing loaded from string")
193
return loads(f.read())