3 Copyright (c) 2007 Jan-Klaas Kollhof
5 This file is part of jsonrpc.
7 jsonrpc is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 This software is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with this software; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
45 StringEscapeRE= re.compile(r'[\x00-\x19\\"/\b\f\n\r\t]')
46 Digits = ['0', '1', '2','3','4','5','6','7','8','9']
49 class JSONEncodeException(Exception):
50 def __init__(self, obj):
51 Exception.__init__(self)
55 return "Object not encodeable: %s" % self.obj
58 class JSONDecodeException(Exception):
59 def __init__(self, message):
60 Exception.__init__(self)
61 self.message = message
67 def escapeChar(match):
70 replacement = CharReplacements[c]
80 return unicode("".join([part for part in dumpParts (obj)]))
86 elif objType is BooleanType:
91 elif objType is DictionaryType:
94 for (key, value) in obj.items():
99 yield u'"' + StringEscapeRE.sub(escapeChar, key) +u'":'
100 for part in dumpParts (value):
103 elif objType in StringTypes:
104 yield u'"' + StringEscapeRE.sub(escapeChar, obj) +u'"'
106 elif objType in [TupleType, ListType, GeneratorType]:
114 for part in dumpParts (item):
117 elif objType in [IntType, LongType, FloatType]:
120 raise JSONEncodeException(obj)
132 if not currCharIsNext:
134 while(c in [' ', '\t', '\r','\n']):
145 value+=EscapeCharToChar[c]
148 hexCode = chars.next() + chars.next() + chars.next() + chars.next()
149 value += unichr(int(hexCode,16))
151 raise JSONDecodeException("Bad Escape Sequence Found")
155 except StopIteration:
156 raise JSONDecodeException("Expected end of String")
169 elif c in Digits or c == '-':
194 raise JSONDecodeException("Expected + or -")
195 except StopIteration:
197 value = numConv("".join(digits))
200 elif c in ['t','f','n']:
201 kw = c+ chars.next() + chars.next() + chars.next()
206 elif kw == 'fals' and chars.next() == 'e':
209 raise JSONDecodeException('Expected Null, False or True')
211 raise JSONDecodeException('Expected []{}," or Number, Null, False or True')
216 if type(top) is ListType:
218 elif type(top) is DictionaryType:
220 elif type(top) in StringTypes:
222 stack[-1][key] = value
224 raise JSONDecodeException("Expected dictionary key, or start of a value")
227 except StopIteration:
228 raise JSONDecodeException("Unexpected end of JSON source")