support json dumps namedict

This commit is contained in:
blueloveTH 2025-03-15 19:43:44 +08:00
parent 61e36941a9
commit c502ce172f
2 changed files with 26 additions and 0 deletions

View File

@ -62,6 +62,15 @@ static bool json__write_dict_kv(py_Ref k, py_Ref v, void* ctx_) {
return json__write_object(ctx->buf, v); return json__write_object(ctx->buf, v);
} }
static bool json__write_namedict_kv(py_Name k, py_Ref v, void* ctx_) {
json__write_dict_kv_ctx* ctx = ctx_;
if(!ctx->first) c11_sbuf__write_cstr(ctx->buf, ", ");
ctx->first = false;
c11_sbuf__write_quoted(ctx->buf, py_name2sv(k), '"');
c11_sbuf__write_cstr(ctx->buf, ": ");
return json__write_object(ctx->buf, v);
}
static bool json__write_object(c11_sbuf* buf, py_TValue* obj) { static bool json__write_object(c11_sbuf* buf, py_TValue* obj) {
switch(obj->type) { switch(obj->type) {
case tp_NoneType: c11_sbuf__write_cstr(buf, "null"); return true; case tp_NoneType: c11_sbuf__write_cstr(buf, "null"); return true;
@ -98,6 +107,14 @@ static bool json__write_object(c11_sbuf* buf, py_TValue* obj) {
c11_sbuf__write_char(buf, '}'); c11_sbuf__write_char(buf, '}');
return true; return true;
} }
case tp_namedict: {
c11_sbuf__write_char(buf, '{');
json__write_dict_kv_ctx ctx = {.buf = buf, .first = true};
bool ok = py_applydict(py_getslot(obj, 0), json__write_namedict_kv, &ctx);
if(!ok) return false;
c11_sbuf__write_char(buf, '}');
return true;
}
default: return TypeError("'%t' object is not JSON serializable", obj->type); default: return TypeError("'%t' object is not JSON serializable", obj->type);
} }
} }

View File

@ -79,3 +79,12 @@ try:
assert False assert False
except TypeError: except TypeError:
assert True assert True
class A:
def __init__(self, a, b):
self.a = a
self.b = b
a = A(1, ['2', False, None])
assert json.dumps(a.__dict__) == '{"a": 1, "b": ["2", false, null]}'