diff --git a/include/json_entities/json_entities.h b/include/json_entities/json_entities.h index 1bc8e0f..a6e10cd 100644 --- a/include/json_entities/json_entities.h +++ b/include/json_entities/json_entities.h @@ -64,4 +64,6 @@ struct json_collection { jentity_t *end; }; +void print_json(const jentity_t *entity, u32 indent); + #endif // !JSON_ENTITIES_H diff --git a/src/json_entities/json_entities.c b/src/json_entities/json_entities.c index 5fcb61d..e9f7e66 100644 --- a/src/json_entities/json_entities.c +++ b/src/json_entities/json_entities.c @@ -1 +1,111 @@ #include "json_entities.h" +#include "aliases.h" +#include "dstring.h" +#include +#include + +void print_json(const jentity_t *entity, u32 indent) { + PERSISTENT i32 indentation = 0; + + dstr_t *key = NULL; + const jval_t *value = NULL; + + if (entity->type == JENTITY_SINGLE) { + value = &(entity->value); + } else { + key = entity->pair.key; + value = &(entity->pair.value); + } + + if (key) { + printf("%*s\"%s\": ", indentation * indent, "", dstr_to_cstr(key)); + } + + switch (value->type) { + case JVAL_COLLECTION: { + const char *open = ""; + const char *close = ""; + + if (value->collection->type == JCOLL_OBJECT) { + open = "{"; + close = "}"; + } else { + open = "["; + close = "]"; + } + + if (key) { + printf("%s\n", open); + } else { + printf("%*s%s\n", indentation * indent, "", open); + } + + ++indentation; + + if (value->collection->begin) { + print_json(value->collection->begin, indent); + } + + --indentation; + + printf("\n%*s%s", indentation * indent, "", close); + + break; + } + case JVAL_STRING: + if (key) { + printf("\"%s\"", dstr_to_cstr(value->string)); + } else { + printf("%*s\"%s\"", indentation * indent, "", + dstr_to_cstr(value->string)); + } + + break; + case JVAL_INTEGER: + if (key) { + printf("%llu", (unsigned long long)value->num_int); + } else { + printf("%*s%llu", indentation * indent, "", + (unsigned long long)value->num_int); + } + + break; + case JVAL_DOUBLE: + if (key) { + printf("%f", value->num_dbl); + } else { + printf("%*s%f", indentation * indent, "", value->num_dbl); + } + + break; + case JVAL_BOOLEAN: + if (key) { + printf("%s", value->boolean ? "true" : "false"); + } else { + printf("%*s%s", indentation * indent, "", + value->boolean ? "true" : "false"); + } + + break; + case JVAL_NULL: + if (key) { + printf("%s", "null"); + } else { + printf("%*s%s", indentation * indent, "", "null"); + } + + break; + case JVAL_EMPTY: + break; + } + + if (entity->next) { + printf(",\n"); + print_json(entity->next, indent); + } + + // Add newline after printing the entire json tree + if (indentation == 0 && entity->parent == NULL && entity->next == NULL) { + printf("\n"); + } +}