Much more reasonable pretty-printing (but still reversed)

This commit is contained in:
Eric Fischer 2014-02-05 17:56:57 -08:00
parent 285f1bf8e6
commit e195aa54c3

51
json.c
View File

@ -28,8 +28,6 @@ typedef struct json_object {
json_hash *hash;
} json_object;
void json_print(json_object *j);
static json_object *add_object(json_type type, json_object *parent) {
json_object *o = malloc(sizeof(struct json_object));
o->type = type;
@ -279,7 +277,14 @@ json_object *json_parse(FILE *f, json_object *current) {
json_error("unrecognized character %c\n", c);
}
void json_print(json_object *j) {
static void indent(int depth) {
int i;
for (i = 0; i < depth; i++) {
printf(" ");
}
}
void json_print(json_object *j, int depth) {
if (j == NULL) {
printf("NULL");
} else if (j->type == JSON_STRING) {
@ -293,25 +298,38 @@ void json_print(json_object *j) {
} else if (j->type == JSON_FALSE) {
printf("false");
} else if (j->type == JSON_HASH) {
printf("{");
printf("{\n");
indent(depth + 1);
json_hash *h = j->hash;
while (h != NULL) {
json_print(h->key);
printf(":");
json_print(h->value);
printf(",");
json_print(h->key, depth + 1);
printf(" : ");
json_print(h->value, depth + 1);
if (h->next != NULL) {
printf(",\n");
indent(depth + 1);
}
h = h->next;
}
printf("\n");
indent(depth);
printf("}");
} else if (j->type == JSON_ARRAY) {
printf("[");
printf("[\n");
indent(depth + 1);
json_array *a = j->array;
while (a != NULL) {
json_print(a->object);
printf(",");
json_print(a->object, depth + 1);
if (a->next != NULL) {
printf(",\n");
indent(depth + 1);
}
a = a->next;
}
printf("\n");
indent(depth);
printf("]");
} else {
printf("what type? %d", j->type);
@ -322,13 +340,10 @@ int main() {
json_object *j = NULL;
while ((j = json_parse(stdin, j)) != NULL) {
#if 0
if (j->parent != NULL) {
printf("parent: ");
json_print(j->parent);
if (j->parent == NULL) {
json_print(j, 0);
printf("\n");
j = NULL;
}
#endif
json_print(j);
printf("\n");
}
}