Skip to content

Commit 599a937

Browse files
committed
Tests and conformance for object.
1 parent 0aec4da commit 599a937

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

jsonfsm.py

+14-3
Original file line numberDiff line numberDiff line change
@@ -265,11 +265,11 @@ def object_fsm():
265265
if c != '{':
266266
raise JSONParseError("Objects must begin with {")
267267

268-
while c != '}':
268+
c = (yield NOT_PARSED_YET)
269+
while c.isspace():
269270
c = (yield NOT_PARSED_YET)
270-
while c.isspace():
271-
c = (yield NOT_PARSED_YET)
272271

272+
while c != '}':
273273
# parse attribute key
274274
key = NOT_PARSED_YET
275275
sp = string_fsm()
@@ -288,6 +288,7 @@ def object_fsm():
288288
c = (yield NOT_PARSED_YET)
289289

290290
# parse value
291+
value = NOT_PARSED_YET
291292
vp = value_fsm()
292293

293294
# look out for , and } since they act as delimiters for numbers
@@ -298,6 +299,16 @@ def object_fsm():
298299
while c.isspace():
299300
c = (yield NOT_PARSED_YET)
300301

302+
# if we stopped at a , advance until the start of the next key/value
303+
# pair (and raise exception if the object ends)
304+
if c == ',':
305+
c = (yield NOT_PARSED_YET)
306+
while c.isspace():
307+
c = (yield NOT_PARSED_YET)
308+
309+
if c == '}':
310+
raise JSONParseError("Extra , before } in object")
311+
301312
obj[key] = value
302313

303314
yield obj

test.py

+27
Original file line numberDiff line numberDiff line change
@@ -105,5 +105,32 @@ def test_invalid_arrays(self):
105105
jsonfsm.loads,
106106
json)
107107

108+
class TestObject(unittest.TestCase):
109+
def setUp(self):
110+
self.valid = (
111+
('{}', {}),
112+
('{"one": 1}', {u"one": 1.0}),
113+
('{ "one" :1, "two": 2}', {u"one":1.0, u"two":2.0}),
114+
('{"delimiter": "}" }', {u"delimiter": u"}"}),
115+
('{"nested": {"object": "here"}}', {u"nested": {u"object": u"here"}}),
116+
)
117+
118+
self.invalid = (
119+
"{,}",
120+
'{"key":}',
121+
'{:"value"}',
122+
'{"extra" : "comma",}',
123+
)
124+
125+
def test_valid_objects(self):
126+
for json, expected in self.valid:
127+
self.assertEquals(jsonfsm.loads(json), expected)
128+
129+
def test_invalid_objects(self):
130+
for json in self.invalid:
131+
self.assertRaises(jsonfsm.JSONParseError,
132+
jsonfsm.loads,
133+
json)
134+
108135
if __name__ == "__main__":
109136
unittest.main()

0 commit comments

Comments
 (0)