jshn: pretty print indented output with jshn -i -w

Signed-off-by: John Crispin <blogic@openwrt.org>
This commit is contained in:
John Crispin 2014-08-04 19:26:18 +02:00
parent 042f1a2546
commit dffbc09baf
2 changed files with 22 additions and 7 deletions

View file

@ -51,7 +51,7 @@ IF(EXISTS ${json})
TARGET_LINK_LIBRARIES(blobmsg_json ubox ${json}) TARGET_LINK_LIBRARIES(blobmsg_json ubox ${json})
ADD_EXECUTABLE(jshn jshn.c) ADD_EXECUTABLE(jshn jshn.c)
TARGET_LINK_LIBRARIES(jshn ${json}) TARGET_LINK_LIBRARIES(jshn blobmsg_json ${json})
ADD_LIBRARY(json_script SHARED json_script.c) ADD_LIBRARY(json_script SHARED json_script.c)
TARGET_LINK_LIBRARIES(json_script ubox) TARGET_LINK_LIBRARIES(json_script ubox)

27
jshn.c
View file

@ -27,8 +27,13 @@
#include <getopt.h> #include <getopt.h>
#include "list.h" #include "list.h"
#include "blob.h"
#include "blobmsg_json.h"
#define MAX_VARLEN 256 #define MAX_VARLEN 256
static struct blob_buf b = { 0 };
static const char *var_prefix = ""; static const char *var_prefix = "";
static int var_prefix_len = 0; static int var_prefix_len = 0;
@ -249,30 +254,37 @@ out:
return obj; return obj;
} }
static int jshn_format(bool no_newline) static int jshn_format(bool no_newline, bool indent)
{ {
json_object *obj; json_object *obj;
const char *output;
obj = json_object_new_object(); obj = json_object_new_object();
jshn_add_objects(obj, "JSON_VAR", false); jshn_add_objects(obj, "JSON_VAR", false);
fprintf(stdout, "%s%s", json_object_to_json_string(obj), output = json_object_to_json_string(obj);
no_newline ? "" : "\n"); if (indent) {
blob_buf_init(&b, 0);
blobmsg_add_json_from_string(&b, output);
output = blobmsg_format_json_indent(b.head, 1, 0);
}
fprintf(stdout, "%s%s", output, no_newline ? "" : "\n");
json_object_put(obj); json_object_put(obj);
return 0; return 0;
} }
static int usage(const char *progname) static int usage(const char *progname)
{ {
fprintf(stderr, "Usage: %s [-n] -r <message>|-w\n", progname); fprintf(stderr, "Usage: %s [-n] [-i] -r <message>|-w\n", progname);
return 2; return 2;
} }
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
bool no_newline = false; bool no_newline = false;
bool indent = false;
int ch; int ch;
while ((ch = getopt(argc, argv, "p:nr:w")) != -1) { while ((ch = getopt(argc, argv, "p:nir:w")) != -1) {
switch(ch) { switch(ch) {
case 'p': case 'p':
var_prefix = optarg; var_prefix = optarg;
@ -281,10 +293,13 @@ int main(int argc, char **argv)
case 'r': case 'r':
return jshn_parse(optarg); return jshn_parse(optarg);
case 'w': case 'w':
return jshn_format(no_newline); return jshn_format(no_newline, indent);
case 'n': case 'n':
no_newline = true; no_newline = true;
break; break;
case 'i':
indent = true;
break;
default: default:
return usage(argv[0]); return usage(argv[0]);
} }