From f0a490fcb1fa51a656883737b1b8f100a6c827c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Schr=C3=B6der?= Date: Tue, 13 Sep 2016 22:19:53 +0200 Subject: [PATCH] fix creation of json from a blob that does not represent a valid table (first check that it is a table, and if not then output it as an array) --- src/blob_json.c | 15 +++++++++++++-- test/json.c | 7 +++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/blob_json.c b/src/blob_json.c index c60c5b6..01c725e 100644 --- a/src/blob_json.c +++ b/src/blob_json.c @@ -269,11 +269,21 @@ static void blob_format_json_list(struct strbuf *s, const struct blob_field *att const struct blob_field *pos; bool first = true; + // just validate first that we really have a table and if not then we just output it as an array. + for(pos = blob_field_first_child(attr); pos; pos = blob_field_next_child(attr, pos)){ + if(!array && blob_field_type(pos) != BLOB_FIELD_STRING){ + array = true; + break; + } + // for kv we need to pop the value here as well + if(!array) + pos = blob_field_next_child(attr, pos); + } + blob_puts(s, (array ? "[" : "{" ), 1); s->indent_level++; add_separator(s); - //__blob_for_each_attr(pos, attr, rem) { for(pos = blob_field_first_child(attr); pos; pos = blob_field_next_child(attr, pos)){ if (!first) { blob_puts(s, ",", 1); @@ -282,12 +292,13 @@ static void blob_format_json_list(struct strbuf *s, const struct blob_field *att if(!array){ blob_format_string(s, blob_field_data(pos)); - blob_puts(s, ": ", s->indent ? 2 : 1); + blob_puts(s, ":", s->indent ? 2 : 1); pos = blob_field_next_child(attr, pos); } blob_format_element(s, pos, array, false); first = false; } + s->indent_level--; add_separator(s); blob_puts(s, (array ? "]" : "}"), 1); diff --git a/test/json.c b/test/json.c index 3b1d1fa..39accdf 100644 --- a/test/json.c +++ b/test/json.c @@ -33,11 +33,12 @@ int main(void){ blob_put_int(&blob, 5000000000lu); blob_close_array(&blob, o); + char *json = blob_to_json(&blob); + printf("json: %s\n", json); + const struct blob_field *out[8]; TEST(blob_field_parse(blob_head(&blob), "isifssta", out, 8)); - char *json = blob_to_json(&blob); - TEST(strcmp("[1,\"foo\",243,3.141593e+00,\"copyme\",\"copyme\",{\"one\":1,\"two\":2,\"three\":3},[100,200,1000,70000,5000000000]]", json) == 0); struct blob b2; @@ -50,6 +51,8 @@ int main(void){ free(json); free(json2); + blob_free(&blob); + return 0; }