provide common json output formatter
Formatting JSON is moderately painful.
Provide a simple API to do the syntax formatting.
diff --git a/misc/lnstat.c b/misc/lnstat.c
index 0385cbb..2cbd789 100644
--- a/misc/lnstat.c
+++ b/misc/lnstat.c
@@ -36,6 +36,7 @@
#include <string.h>
#include <getopt.h>
+#include <json_writer.h>
#include "lnstat.h"
static struct option opts[] = {
@@ -49,6 +50,7 @@
{ "keys", 1, NULL, 'k' },
{ "subject", 1, NULL, 's' },
{ "width", 1, NULL, 'w' },
+ { "oneline", 0, NULL, 0 },
};
static int usage(char *name, int exit_code)
@@ -107,25 +109,17 @@
static void print_json(FILE *of, const struct lnstat_file *lnstat_files,
const struct field_params *fp)
{
+ json_writer_t *jw = jsonw_new(of);
int i;
- const char *sep;
- const char *base = NULL;
- fputs("{\n", of);
+ jsonw_start_object(jw);
for (i = 0; i < fp->num; i++) {
const struct lnstat_field *lf = fp->params[i].lf;
- if (!base || lf->file->basename != base) {
- if (base) fputs("},\n", of);
- base = lf->file->basename;
- sep = "\n\t";
- fprintf(of, " \"%s\":{", base);
- }
- fprintf(of, "%s\"%s\":%lu", sep,
- lf->name, lf->result);
- sep = ",\n\t";
+ jsonw_uint_field(jw, lf->name, lf->result);
}
- fputs("}\n}\n", of);
+ jsonw_end_object(jw);
+ jsonw_destroy(&jw);
}
/* find lnstat_field according to user specification */
@@ -272,7 +266,7 @@
num_req_files = 1;
}
- while ((c = getopt_long(argc, argv,"Vc:djf:h?i:k:s:w:",
+ while ((c = getopt_long(argc, argv,"Vc:djpf:h?i:k:s:w:",
opts, NULL)) != -1) {
int len = 0;
char *tmp, *tok;