Skip to content

Commit af48f30

Browse files
committed
extmod/modjson: Allow json.loads() to preserve dict order.
When MICROPY_PY_JSON_ORDERED_DICT is enabled.
1 parent 27b7bf3 commit af48f30

File tree

4 files changed

+23
-0
lines changed

4 files changed

+23
-0
lines changed

extmod/modjson.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,12 @@ static mp_obj_t mod_json_load(mp_obj_t stream_obj) {
283283
break;
284284
case '{':
285285
next = mp_obj_new_dict(0);
286+
#if MICROPY_PY_JSON_ORDERED_DICT
287+
// keep the locals ordered
288+
mp_obj_dict_t *dict = MP_OBJ_TO_PTR(next);
289+
dict->map.is_ordered = 1;
290+
#endif
291+
286292
enter = true;
287293
break;
288294
case '}':

ports/unix/variants/coverage/mpconfigvariant.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
#undef MICROPY_VFS_ROM_IOCTL
4646
#define MICROPY_VFS_ROM_IOCTL (1)
4747
#define MICROPY_PY_CRYPTOLIB_CTR (1)
48+
#define MICROPY_PY_JSON_ORDERED_DICT (1)
4849
#define MICROPY_SCHEDULER_STATIC_NODES (1)
4950

5051
// Enable os.uname for attrtuple coverage test

py/mpconfig.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1912,6 +1912,10 @@ typedef time_t mp_timestamp_t;
19121912
#define MICROPY_PY_JSON (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES)
19131913
#endif
19141914

1915+
#ifndef MICROPY_PY_JSON_ORDERED_DICT
1916+
#define MICROPY_PY_JSON_ORDERED_DICT (0)
1917+
#endif
1918+
19151919
// Whether to support the "separators" argument to dump, dumps
19161920
#ifndef MICROPY_PY_JSON_SEPARATORS
19171921
#define MICROPY_PY_JSON_SEPARATORS (1)

tests/extmod/json_loads.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44
print("SKIP")
55
raise SystemExit
66

7+
try:
8+
extra_coverage
9+
is_coverage = True
10+
except NameError:
11+
is_coverage = False
12+
713

814
def my_print(o):
915
if isinstance(o, dict):
@@ -33,6 +39,12 @@ def my_print(o):
3339
my_print(json.loads('"abc\\tdef"'))
3440
my_print(json.loads('"abc\\uabcd"'))
3541

42+
if is_coverage: # Has ordered json loads enabled
43+
o = json.loads('{"b":null, "c":false, "e":true}')
44+
print(list(o.items()) == list(sorted(o.items())))
45+
else:
46+
print(True)
47+
3648
# whitespace handling
3749
my_print(json.loads('{\n\t"a":[]\r\n, "b":[1], "c":{"3":4} \n\r\t\r\r\r\n}'))
3850

0 commit comments

Comments
 (0)