From 7471093f67ed864467f4e4eeebe2179933f91253 Mon Sep 17 00:00:00 2001 From: Felix Van der Jeugt Date: Fri, 4 Nov 2022 08:21:05 +0100 Subject: [PATCH] add null (NIL) and negative numbers --- json.c | 33 ++++++++++++++++++++++++--------- json.h | 2 +- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/json.c b/json.c index 7feb50b..530a725 100644 --- a/json.c +++ b/json.c @@ -6,6 +6,16 @@ #include "sortedmap.h" #include "arraylist.h" +Json * parse_null(FILE *stream) { + Json * json; + if (getc(stream) == 'u' && getc(stream) == 'l' && getc(stream) == 'l') { + json = malloc(sizeof(Json)); + json->type = NIL; + return json; + } + return NULL; +} + Json * parse_true(FILE *stream) { Json * json; if (getc(stream) == 'r' && getc(stream) == 'u' && getc(stream) == 'e') { @@ -28,7 +38,8 @@ Json * parse_false(FILE *stream) { return NULL; } -Json * parse_number(FILE *stream) { +/* TODO: scientific notation */ +Json * parse_number(FILE *stream, int sign) { Json * json; long num = 0, den = 0; char c; @@ -58,12 +69,13 @@ Json * parse_number(FILE *stream) { if (c != EOF) ungetc(c, stream); json = malloc(sizeof(Json)); json->type = NUMBER; - json->value.number = num * 1.0 / den; + json->value.number = sign * num * 1.0 / den; return json; } } } +/* TODO: more escaped characters, unicode? */ Json * parse_string(FILE *stream) { int i = 0, cap = 10; char * buffer = calloc(cap, sizeof(char)); @@ -71,7 +83,6 @@ Json * parse_string(FILE *stream) { int escaped = 0; Json * json; while ((c = getc(stream)) != EOF) { - printf("char: %c, buffer: %s, i: %d\n", c, buffer, i); switch (c) { case '\\': escaped = 1; @@ -114,6 +125,10 @@ Json * json_parse(FILE *stream) { return parse_true(stream); case 'f': return parse_false(stream); + case 'n': + return parse_null(stream); + case '-': + return parse_number(stream, -1); case '0': case '1': case '2': @@ -125,7 +140,7 @@ Json * json_parse(FILE *stream) { case '8': case '9': ungetc(c, stream); - return parse_number(stream); + return parse_number(stream, 1); case ' ': case '\n': case '\t': @@ -152,6 +167,9 @@ void json_print(Json *this, FILE *stream) { int i; struct printacc acc = { NULL, 0 }; switch (this->type) { + case NIL: + fprintf(stream, "null"); + break; case BOOLEAN: fprintf(stream, this->value.boolean == 0 ? "false" : "true"); break; @@ -183,16 +201,13 @@ void json_print(Json *this, FILE *stream) { void json_free(Json *this) { switch (this->type) { + case NIL: case BOOLEAN: - /* TODO */ + case NUMBER: break; case STRING: - /* TODO */ free(this->value.string); break; - case NUMBER: - /* TODO */ - break; case LIST: /* TODO */ break; diff --git a/json.h b/json.h index c868ac8..5bf3e28 100644 --- a/json.h +++ b/json.h @@ -2,7 +2,7 @@ #define JSON_HEADER #include "sortedmap.h" #include "arraylist.h" -enum jsontype { BOOLEAN, STRING, NUMBER, LIST, MAP }; +enum jsontype { NIL, BOOLEAN, STRING, NUMBER, LIST, MAP }; typedef struct json { enum jsontype type;