extmod/modujson: Implement ujson.dump() function.

This commit is contained in:
Damien George 2018-02-06 15:35:52 +11:00
parent 9e8b7b1b63
commit d9bca1f7bd
2 changed files with 29 additions and 0 deletions

View File

@ -34,6 +34,16 @@
#if MICROPY_PY_UJSON #if MICROPY_PY_UJSON
STATIC mp_obj_t mod_ujson_dump(mp_obj_t obj, mp_obj_t stream) {
if (!MP_OBJ_IS_OBJ(stream)) {
mp_raise_TypeError(NULL);
}
mp_print_t print = {MP_OBJ_TO_PTR(stream), mp_stream_write_adaptor};
mp_obj_print_helper(&print, obj, PRINT_JSON);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ujson_dump_obj, mod_ujson_dump);
STATIC mp_obj_t mod_ujson_dumps(mp_obj_t obj) { STATIC mp_obj_t mod_ujson_dumps(mp_obj_t obj) {
vstr_t vstr; vstr_t vstr;
mp_print_t print; mp_print_t print;
@ -283,6 +293,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_loads_obj, mod_ujson_loads);
STATIC const mp_rom_map_elem_t mp_module_ujson_globals_table[] = { STATIC const mp_rom_map_elem_t mp_module_ujson_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ujson) }, { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ujson) },
{ MP_ROM_QSTR(MP_QSTR_dump), MP_ROM_PTR(&mod_ujson_dump_obj) },
{ MP_ROM_QSTR(MP_QSTR_dumps), MP_ROM_PTR(&mod_ujson_dumps_obj) }, { MP_ROM_QSTR(MP_QSTR_dumps), MP_ROM_PTR(&mod_ujson_dumps_obj) },
{ MP_ROM_QSTR(MP_QSTR_load), MP_ROM_PTR(&mod_ujson_load_obj) }, { MP_ROM_QSTR(MP_QSTR_load), MP_ROM_PTR(&mod_ujson_load_obj) },
{ MP_ROM_QSTR(MP_QSTR_loads), MP_ROM_PTR(&mod_ujson_loads_obj) }, { MP_ROM_QSTR(MP_QSTR_loads), MP_ROM_PTR(&mod_ujson_loads_obj) },

View File

@ -0,0 +1,18 @@
try:
from uio import StringIO
import ujson as json
except:
try:
from io import StringIO
import json
except ImportError:
print("SKIP")
raise SystemExit
s = StringIO()
json.dump(False, s)
print(s.getvalue())
s = StringIO()
json.dump({"a": (2, [3, None])}, s)
print(s.getvalue())