Skip to content

Commit c119785

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

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
@@ -282,6 +282,12 @@ static mp_obj_t mod_json_load(mp_obj_t stream_obj) {
282282
break;
283283
case '{':
284284
next = mp_obj_new_dict(0);
285+
#if MICROPY_PY_JSON_ORDERED_DICT
286+
// keep the locals ordered
287+
mp_obj_dict_t *dict = MP_OBJ_TO_PTR(next);
288+
dict->map.is_ordered = 1;
289+
#endif
290+
285291
enter = true;
286292
break;
287293
case '}':

ports/unix/variants/coverage/mpconfigvariant.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,4 @@
4444
#undef MICROPY_VFS_ROM_IOCTL
4545
#define MICROPY_VFS_ROM_IOCTL (1)
4646
#define MICROPY_PY_CRYPTOLIB_CTR (1)
47+
#define MICROPY_PY_JSON_ORDERED_DICT (1)

py/mpconfig.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1697,6 +1697,10 @@ typedef double mp_float_t;
16971697
#define MICROPY_PY_JSON (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES)
16981698
#endif
16991699

1700+
#ifndef MICROPY_PY_JSON_ORDERED_DICT
1701+
#define MICROPY_PY_JSON_ORDERED_DICT (0)
1702+
#endif
1703+
17001704
// Whether to support the "separators" argument to dump, dumps
17011705
#ifndef MICROPY_PY_JSON_SEPARATORS
17021706
#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)