aboutsummaryrefslogtreecommitdiff
path: root/py/objdict.c
diff options
context:
space:
mode:
authorEric Poulsen <eric@zyxod.com>2019-07-16 14:29:22 -0700
committerDamien George <damien.p.george@gmail.com>2019-07-30 16:34:27 +1000
commit01054f20925b92229402750979864f8d38a76916 (patch)
tree4a09b0156afc6394270f471e30475efe41a8eeb5 /py/objdict.c
parent8f55a8fab625d645b189c471f3a32c0de7e5ef7d (diff)
py/objdict: Quote non-string types when used as keys in JSON output.
JSON requires that keys of objects be strings. CPython will therefore automatically quote simple types (NoneType, bool, int, float) when they are used directly as keys in JSON output. To prevent subtle bugs and emit compliant JSON, MicroPython should at least test for such keys so they aren't silently let through. Then doing the actual quoting is a similar cost to raising an exception, so that's what is implemented by this patch. Fixes issue #4790.
Diffstat (limited to 'py/objdict.c')
-rw-r--r--py/objdict.c8
1 files changed, 8 insertions, 0 deletions
diff --git a/py/objdict.c b/py/objdict.c
index 0a223f731..02a2346fd 100644
--- a/py/objdict.c
+++ b/py/objdict.c
@@ -31,6 +31,7 @@
#include "py/runtime.h"
#include "py/builtin.h"
#include "py/objtype.h"
+#include "py/objstr.h"
#define mp_obj_is_dict_type(o) (mp_obj_is_obj(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new)
@@ -70,7 +71,14 @@ STATIC void dict_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_
mp_print_str(print, ", ");
}
first = false;
+ bool add_quote = MICROPY_PY_UJSON && kind == PRINT_JSON && !mp_obj_is_str_or_bytes(next->key);
+ if (add_quote) {
+ mp_print_str(print, "\"");
+ }
mp_obj_print_helper(print, next->key, kind);
+ if (add_quote) {
+ mp_print_str(print, "\"");
+ }
mp_print_str(print, ": ");
mp_obj_print_helper(print, next->value, kind);
}