From f48554d48b002ac2881569ecb088aeef710f9369 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Wei=C3=9Fschuh?= Date: Wed, 26 May 2021 13:30:31 +0200 Subject: [PATCH] libsmartcols: add support for optional boolean values MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These default to `null` instead of `false`. Signed-off-by: Thomas Weißschuh --- include/jsonwrt.h | 2 ++ lib/jsonwrt.c | 8 ++++++++ libsmartcols/src/libsmartcols.h.in | 3 ++- libsmartcols/src/print.c | 15 ++++++++++----- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/include/jsonwrt.h b/include/jsonwrt.h index 5be2d70cd..4587b60a9 100644 --- a/include/jsonwrt.h +++ b/include/jsonwrt.h @@ -40,5 +40,7 @@ void ul_jsonwrt_value_u64(struct ul_jsonwrt *fmt, const char *name, uint64_t data); void ul_jsonwrt_value_boolean(struct ul_jsonwrt *fmt, const char *name, int data); +void ul_jsonwrt_value_null(struct ul_jsonwrt *fmt, + const char *name); #endif /* UTIL_LINUX_JSONWRT_H */ diff --git a/lib/jsonwrt.c b/lib/jsonwrt.c index f2003e808..9331dec0e 100644 --- a/lib/jsonwrt.c +++ b/lib/jsonwrt.c @@ -214,3 +214,11 @@ void ul_jsonwrt_value_boolean(struct ul_jsonwrt *fmt, fputs(data ? "true" : "false", fmt->out); ul_jsonwrt_value_close(fmt); } + +void ul_jsonwrt_value_null(struct ul_jsonwrt *fmt, + const char *name) +{ + ul_jsonwrt_value_open(fmt, name); + fputs("null", fmt->out); + ul_jsonwrt_value_close(fmt); +} diff --git a/libsmartcols/src/libsmartcols.h.in b/libsmartcols/src/libsmartcols.h.in index 4c17eb1dc..8c4ba814e 100644 --- a/libsmartcols/src/libsmartcols.h.in +++ b/libsmartcols/src/libsmartcols.h.in @@ -95,7 +95,8 @@ enum { SCOLS_JSON_NUMBER = 1, SCOLS_JSON_BOOLEAN = 2, SCOLS_JSON_ARRAY_STRING = 3, /* e.g. for multi-line (SCOLS_FL_WRAP) cells */ - SCOLS_JSON_ARRAY_NUMBER = 4 + SCOLS_JSON_ARRAY_NUMBER = 4, + SCOLS_JSON_BOOLEAN_OPTIONAL = 5, }; /* diff --git a/libsmartcols/src/print.c b/libsmartcols/src/print.c index 9f6014848..6f6d88e55 100644 --- a/libsmartcols/src/print.c +++ b/libsmartcols/src/print.c @@ -524,11 +524,16 @@ static void print_json_data(struct libscols_table *tb, ul_jsonwrt_value_raw(&tb->json, name, data); break; case SCOLS_JSON_BOOLEAN: - /* name: true|false */ - ul_jsonwrt_value_boolean(&tb->json, name, - !*data ? 0 : - *data == '0' ? 0 : - *data == 'N' || *data == 'n' ? 0 : 1); + case SCOLS_JSON_BOOLEAN_OPTIONAL: + /* name: true|false|null */ + if (cl->json_type == SCOLS_JSON_BOOLEAN_OPTIONAL && (!*data || !strcmp(data, "-"))) { + ul_jsonwrt_value_null(&tb->json, name); + } else { + ul_jsonwrt_value_boolean(&tb->json, name, + !*data ? 0 : + *data == '0' ? 0 : + *data == 'N' || *data == 'n' ? 0 : 1); + } break; case SCOLS_JSON_ARRAY_STRING: case SCOLS_JSON_ARRAY_NUMBER: