Bläddra i källkod

support json dumps namedict

blueloveTH 11 månader sedan
förälder
incheckning
c502ce172f
2 ändrade filer med 26 tillägg och 0 borttagningar
  1. 17 0
      src/modules/json.c
  2. 9 0
      tests/72_json.py

+ 17 - 0
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);
     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);
     }
     }
 }
 }

+ 9 - 0
tests/72_json.py

@@ -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]}'