Stringify feature properties that are arrays or hashes

This commit is contained in:
Eric Fischer
2016-01-27 14:29:34 -08:00
parent baf576f257
commit 167beae307
5 changed files with 115 additions and 3 deletions
+97
View File
@@ -194,6 +194,21 @@ static void string_append(struct string *s, char c) {
s->buf[s->n] = '\0';
}
static void string_append_string(struct string *s, char *add) {
int len = strlen(add);
if (s->n + len + 1 >= s->nalloc) {
s->nalloc += 500 + len;
s->buf = realloc(s->buf, s->nalloc);
}
for (; *add != '\0'; add++) {
s->buf[s->n++] = *add;
}
s->buf[s->n] = '\0';
}
static void string_free(struct string *s) {
free(s->buf);
}
@@ -621,3 +636,85 @@ void json_disconnect(json_object *o) {
o->parent = NULL;
}
static void json_print_one(struct string *val, json_object *o) {
if (o == NULL) {
string_append_string(val, "NULL");
} else if (o->type == JSON_STRING) {
string_append(val, '\"');
char *cp;
for (cp = o->string; *cp != '\0'; cp++) {
if (*cp == '\\' || *cp == '"') {
string_append(val, '\\');
string_append(val, *cp);
} else if (*cp >= 0 && *cp < ' ') {
char *s;
if (asprintf(&s, "\\u%04x", *cp) >= 0) {
string_append_string(val, s);
free(s);
}
} else {
string_append(val, *cp);
}
}
string_append(val, '\"');
} else if (o->type == JSON_NUMBER) {
char *s;
if (asprintf(&s, "%f", o->number) >= 0) {
string_append_string(val, s);
free(s);
}
} else if (o->type == JSON_NULL) {
string_append_string(val, "null");
} else if (o->type == JSON_TRUE) {
string_append_string(val, "true");
} else if (o->type == JSON_FALSE) {
string_append_string(val, "false");
} else if (o->type == JSON_HASH) {
string_append(val, '}');
} else if (o->type == JSON_ARRAY) {
string_append(val, ']');
}
}
static void json_print(struct string *val, json_object *o) {
if (o == NULL) {
// Hash value in incompletely read hash
string_append_string(val, "NULL");
} else if (o->type == JSON_HASH) {
string_append(val, '{');
int i;
for (i = 0; i < o->length; i++) {
json_print(val, o->keys[i]);
string_append(val, ':');
json_print(val, o->values[i]);
if (i + 1 < o->length) {
string_append(val, ',');
}
}
string_append(val, '}');
} else if (o->type == JSON_ARRAY) {
string_append(val, '[');
int i;
for (i = 0; i < o->length; i++) {
json_print(val, o->array[i]);
if (i + 1 < o->length) {
string_append(val, ',');
}
}
string_append(val, ']');
} else {
json_print_one(val, o);
}
}
char *json_stringify(json_object *o) {
struct string val;
string_init(&val);
json_print(&val, o);
return val.buf;
}