From 1f8212dadf18e0358244c705f46bf7c0d8267522 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Sat, 5 Apr 2025 14:48:51 +0800 Subject: [PATCH] fix json indent --- src/modules/json.c | 15 ++++++++++++++- tests/73_json_indent.py | 5 +++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/modules/json.c b/src/modules/json.c index b116091e..e46fdd76 100644 --- a/src/modules/json.c +++ b/src/modules/json.c @@ -53,6 +53,10 @@ static void json__write_indent(c11_sbuf* buf, int n_spaces) { static bool json__write_array(c11_sbuf* buf, py_TValue* arr, int length, int indent, int depth) { c11_sbuf__write_char(buf, '['); + if(length == 0) { + c11_sbuf__write_char(buf, ']'); + return true; + } if(indent > 0) c11_sbuf__write_char(buf, '\n'); int n_spaces = indent * depth; const char* sep = indent > 0 ? ",\n" : ", "; @@ -125,6 +129,10 @@ static bool json__write_object(c11_sbuf* buf, py_TValue* obj, int indent, int de } case tp_dict: { c11_sbuf__write_char(buf, '{'); + if(py_dict_len(obj) == 0) { + c11_sbuf__write_char(buf, '}'); + return true; + } if(indent > 0) c11_sbuf__write_char(buf, '\n'); json__write_dict_kv_ctx ctx = {.buf = buf, .first = true, @@ -140,13 +148,18 @@ static bool json__write_object(c11_sbuf* buf, py_TValue* obj, int indent, int de return true; } case tp_namedict: { + py_Ref original = py_getslot(obj, 0); c11_sbuf__write_char(buf, '{'); + if(PyObject__dict(original->_obj)->length == 0) { + c11_sbuf__write_char(buf, '}'); + return true; + } if(indent > 0) c11_sbuf__write_char(buf, '\n'); json__write_dict_kv_ctx ctx = {.buf = buf, .first = true, .indent = indent, .depth = depth + 1}; - bool ok = py_applydict(py_getslot(obj, 0), json__write_namedict_kv, &ctx); + bool ok = py_applydict(original, json__write_namedict_kv, &ctx); if(!ok) return false; if(indent > 0) { c11_sbuf__write_char(buf, '\n'); diff --git a/tests/73_json_indent.py b/tests/73_json_indent.py index 3d8b4ea6..154c0c9b 100644 --- a/tests/73_json_indent.py +++ b/tests/73_json_indent.py @@ -1,5 +1,10 @@ import json +# test empty +assert json.dumps({}, indent=2) == '{}' +assert json.dumps([], indent=2) == '[]' +assert json.dumps(object().__dict__, indent=2) == '{}' + assert json.dumps([1, 2, [3, 4], 5], indent=2) == '[\n 1,\n 2,\n [\n 3,\n 4\n ],\n 5\n]' a = {