add null (NIL) and negative numbers

This commit is contained in:
Felix Van der Jeugt 2022-11-04 08:21:05 +01:00
parent e8897609b7
commit 7471093f67
No known key found for this signature in database
GPG Key ID: 58B209295023754D
2 changed files with 25 additions and 10 deletions

33
json.c
View File

@ -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;

2
json.h
View File

@ -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;