From c502ce172ff1442288e64d12351dc63b242db467 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Sat, 15 Mar 2025 19:43:44 +0800 Subject: [PATCH] support json dumps namedict --- src/modules/json.c | 17 +++++++++++++++++ tests/72_json.py | 9 +++++++++ 2 files changed, 26 insertions(+) diff --git a/src/modules/json.c b/src/modules/json.c index 61e3c8d3..53f8e434 100644 --- a/src/modules/json.c +++ b/src/modules/json.c @@ -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); } +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) { switch(obj->type) { 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, '}'); 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); } } diff --git a/tests/72_json.py b/tests/72_json.py index 3b5f499f..04783357 100644 --- a/tests/72_json.py +++ b/tests/72_json.py @@ -79,3 +79,12 @@ try: assert False except TypeError: 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]}' \ No newline at end of file