diff options
author | Damien George <damien.p.george@gmail.com> | 2014-09-17 22:56:34 +0100 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2014-09-17 22:56:34 +0100 |
commit | 612045f53f7e5edf9faa359ee9ee52d490d58000 (patch) | |
tree | a021612e31ff6275246514405c4a8421c6eff5d7 /py/objstr.c | |
parent | 8a9b999f1c9a0edf84b2507940efb8deaaa380b8 (diff) |
py: Add native json printing using existing print framework.
Also add start of ujson module with dumps implemented. Enabled in unix
and stmhal ports. Test passes on both.
Diffstat (limited to 'py/objstr.c')
-rw-r--r-- | py/objstr.c | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/py/objstr.c b/py/objstr.c index b2afcdc98..130af8a6a 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -92,9 +92,41 @@ void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *e print(env, "%c", quote_char); } +#if MICROPY_PY_UJSON +STATIC void str_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, mp_uint_t str_len) { + print(env, "\""); + for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) { + if (*s == '"' || *s == '\\' || *s == '/') { + print(env, "\\%c", *s); + } else if (32 <= *s && *s <= 126) { + print(env, "%c", *s); + } else if (*s == '\b') { + print(env, "\\b"); + } else if (*s == '\f') { + print(env, "\\f"); + } else if (*s == '\n') { + print(env, "\\n"); + } else if (*s == '\r') { + print(env, "\\r"); + } else if (*s == '\t') { + print(env, "\\t"); + } else { + print(env, "\\u%04x", *s); + } + } + print(env, "\""); +} +#endif + STATIC void str_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) { GET_STR_DATA_LEN(self_in, str_data, str_len); bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes); + #if MICROPY_PY_UJSON + if (kind == PRINT_JSON) { + str_print_json(print, env, str_data, str_len); + return; + } + #endif if (kind == PRINT_STR && !is_bytes) { print(env, "%.*s", str_len, str_data); } else { |