Skip to content

Commit 2c180f7

Browse files
committed
extmod, ujson: Add test and comment for loads.
1 parent df1e92b commit 2c180f7

2 files changed

Lines changed: 44 additions & 1 deletion

File tree

extmod/modujson.c

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,13 +49,26 @@ STATIC mp_obj_t mod_ujson_dumps(mp_obj_t obj) {
4949
}
5050
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_dumps_obj, mod_ujson_dumps);
5151

52+
// This function implements a simple non-recursive JSON parser.
53+
//
54+
// The JSON specification is at http://www.ietf.org/rfc/rfc4627.txt
55+
// The parser here will parse any valid JSON and return the correct
56+
// corresponding Python object. It allows through a superset of JSON, since
57+
// it treats commas and colons as "whitespace", and doesn't care if
58+
// brackets/braces are correctly paired. It will raise a ValueError if the
59+
// input is outside it's specs.
60+
//
61+
// Most of the work is parsing the primitives (null, false, true, numbers,
62+
// strings). It does 1 pass over the input string and so is easily extended to
63+
// being able to parse from a non-seekable stream. It tries to be fast and
64+
// small in code size, while not using more RAM than necessary.
5265
STATIC mp_obj_t mod_ujson_loads(mp_obj_t obj) {
5366
mp_uint_t len;
5467
const char *s = mp_obj_str_get_data(obj, &len);
5568
const char *top = s + len;
5669
vstr_t vstr;
5770
vstr_init(&vstr, 8);
58-
mp_obj_list_t stack;
71+
mp_obj_list_t stack; // we use a list as a simple stack for nested JSON
5972
stack.len = 0;
6073
stack.items = NULL;
6174
mp_obj_t stack_top = MP_OBJ_NULL;

tests/extmod/ujson_loads.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
try:
2+
import ujson as json
3+
except:
4+
import json
5+
6+
def my_print(o):
7+
if isinstance(o, dict):
8+
print('sorted dict', sorted(o.items()))
9+
else:
10+
print(o)
11+
12+
my_print(json.loads('null'))
13+
my_print(json.loads('false'))
14+
my_print(json.loads('true'))
15+
my_print(json.loads('1'))
16+
my_print(json.loads('1.2'))
17+
my_print(json.loads('1e2'))
18+
my_print(json.loads('-2'))
19+
my_print(json.loads('-2.3'))
20+
my_print(json.loads('-2e3'))
21+
my_print(json.loads('-2e-3'))
22+
my_print(json.loads('"abc\\u0064e"'))
23+
my_print(json.loads('[]'))
24+
my_print(json.loads('[null]'))
25+
my_print(json.loads('[null,false,true]'))
26+
my_print(json.loads(' [ null , false , true ] '))
27+
my_print(json.loads('{}'))
28+
my_print(json.loads('{"a":true}'))
29+
my_print(json.loads('{"a":null, "b":false, "c":true}'))
30+
my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}'))

0 commit comments

Comments
 (0)