From d9d6f434079f842674becdea31521f54655d5bdd Mon Sep 17 00:00:00 2001 From: Stephen Dolan Date: Tue, 11 Sep 2012 15:51:12 +0100 Subject: Pretty-printing of JSON values. --- c/bytecode.c | 2 +- c/jv.h | 4 +++- c/jv_print.c | 38 +++++++++++++++++++++++++++++--------- c/main.c | 8 ++++---- 4 files changed, 37 insertions(+), 15 deletions(-) diff --git a/c/bytecode.c b/c/bytecode.c index 208e82f0..bafd0474 100644 --- a/c/bytecode.c +++ b/c/bytecode.c @@ -58,7 +58,7 @@ void dump_operation(struct bytecode* bc, uint16_t* codeptr) { printf(" %04d", pc + imm); } else if (op->flags & OP_HAS_CONSTANT) { printf(" "); - jv_dump(jv_array_get(jv_copy(bc->constants), imm)); + jv_dump(jv_array_get(jv_copy(bc->constants), imm), 0); } else if (op->flags & OP_HAS_VARIABLE) { uint16_t v = bc->code[pc++]; printf(" v%d", v); diff --git a/c/jv.h b/c/jv.h index 48ae0e0f..ec23262c 100644 --- a/c/jv.h +++ b/c/jv.h @@ -102,7 +102,9 @@ jv jv_object_iter_value(jv, int); int jv_get_refcnt(jv); -void jv_dump(jv); +enum { JV_PRINT_PRETTY = 1, JV_PRINT_ASCII = 2 }; +void jv_dump(jv, int); + jv jv_parse(const char* string); jv jv_parse_sized(const char* string, int length); diff --git a/c/jv_print.c b/c/jv_print.c index e122a5c8..f1ec92fb 100644 --- a/c/jv_print.c +++ b/c/jv_print.c @@ -64,7 +64,9 @@ static void jv_dump_string(jv str, int ascii_only) { assert(c != -1); } -static void jv_dump_term(struct dtoa_context* C, jv x) { +enum { INDENT = 2 }; + +static void jv_dump_term(struct dtoa_context* C, jv x, int flags, int indent) { char buf[JVP_DTOA_FMT_MAX_LEN]; switch (jv_get_kind(x)) { case JV_KIND_INVALID: @@ -99,33 +101,51 @@ static void jv_dump_term(struct dtoa_context* C, jv x) { putchar('"'); break; case JV_KIND_ARRAY: { + if (jv_array_length(jv_copy(x)) == 0) { + printf("[]"); + break; + } printf("["); + if (flags & JV_PRINT_PRETTY) printf("\n%*s", indent+INDENT, ""); for (int i=0; i