summaryrefslogtreecommitdiffhomepage
path: root/lib.c
diff options
context:
space:
mode:
authorJo-Philipp Wich <jo@mein.io>2021-05-04 11:41:17 +0200
committerJo-Philipp Wich <jo@mein.io>2021-05-04 11:49:37 +0200
commitc4d1648ca6c3ac005b75c3b3b0bb79e664bead75 (patch)
treeff0968c366537455aa1d7bfc42dff81549016e31 /lib.c
parentf2eaea3be2ebf87e2837b728e5a0c67eedf296f5 (diff)
lib: add support for pretty printing JSON to printf() and sprintf()
Honour precision specifiers when parsing `J` format strings to enable or disable JSON pretty printing. Signed-off-by: Jo-Philipp Wich <jo@mein.io>
Diffstat (limited to 'lib.c')
-rw-r--r--lib.c22
1 files changed, 19 insertions, 3 deletions
diff --git a/lib.c b/lib.c
index d6889c6..93798b8 100644
--- a/lib.c
+++ b/lib.c
@@ -1210,6 +1210,7 @@ uc_printf_common(uc_vm *vm, size_t nargs, uc_stringbuf_t *buf)
const char *fstr, *last, *p;
uc_type_t t = UC_NULL;
size_t argidx = 1;
+ int i, pad_size;
if (ucv_type(fmt) == UC_STRING)
fstr = ucv_string_get(fmt);
@@ -1339,10 +1340,25 @@ uc_printf_common(uc_vm *vm, size_t nargs, uc_stringbuf_t *buf)
case 'J':
t = UC_STRING;
- if (argidx < nargs)
- arg.s = ucv_to_jsonstring(vm, uc_get_arg(argidx++));
- else
+ pad_size = 0;
+
+ for (i = 0; sfmt + i < fp; i++) {
+ if (sfmt[i] == '.') {
+ pad_size = 1 + atoi(&sfmt[i + 1]);
+ fp = &sfmt[i];
+ break;
+ }
+ }
+
+ if (argidx < nargs) {
+ arg.s = ucv_to_jsonstring_formatted(vm,
+ uc_get_arg(argidx++),
+ pad_size > 0 ? (pad_size > 1 ? ' ' : '\t') : '\0',
+ pad_size > 0 ? (pad_size > 1 ? pad_size - 1 : 1) : 0);
+ }
+ else {
arg.s = NULL;
+ }
arg.s = arg.s ? arg.s : xstrdup("null");