added example

This commit is contained in:
cozis
2022-04-25 15:22:16 +02:00
parent 5f2d32a7e1
commit 3e2c1af45a
4 changed files with 95 additions and 48 deletions
+47 -46
View File
@@ -4,7 +4,52 @@
#include <ctype.h>
#include "xjson.h"
char *load_file(const char *path, int *len)
static char *load_file(const char *path, int *len);
int main(int argc, char **argv)
{
if(argc < 2)
{
fprintf(stderr, "Error: Missing file\n");
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
return 1;
}
int size;
char *data;
data = load_file(argv[1], &size);
if(data == NULL)
{
fprintf(stderr, "Error: Failed to load file\n");
return 1;
}
char pool[65536];
xj_alloc *alloc;
alloc = xj_alloc_using(pool, sizeof(pool), 4096, NULL);
assert(alloc != NULL);
xj_error error;
xj_value *val = xj_decode(data, size, alloc, &error);
if(val == NULL)
{
if(error.off < 0)
fprintf(stderr, "Error: %s\n", error.message);
else
fprintf(stderr, "Error %s:%d:%d: %s\n", argv[1], error.row+1, error.col+1, error.message);
}
else
fprintf(stderr, "OK\n");
xj_alloc_del(alloc);
free(data);
return 0;
}
static char *load_file(const char *path, int *len)
{
FILE *fp = fopen(path, "rb");
@@ -37,48 +82,4 @@ char *load_file(const char *path, int *len)
if(len)
*len = len_;
return data;
}
int main(int argc, char **argv)
{
if(argc < 2)
{
fprintf(stderr, "Error: Missing file\n");
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
return 1;
}
int size;
char *data = load_file(argv[1], &size);
if(data == NULL)
{
fprintf(stderr, "Error: Failed to load file\n");
return 1;
}
char pool[65536];
xj_error error;
xj_alloc *alloc = xj_alloc_using(pool, sizeof(pool), 4096, NULL);
assert(alloc != NULL);
xj_value *val = xj_decode(data, size, alloc, &error);
if(val == NULL)
{
if(error.off < 0)
fprintf(stderr, "Error: %s\n", error.message);
else
fprintf(stderr, "Error %s:%d:%d: %s\n", argv[1], error.row+1, error.col+1, error.message);
xj_alloc_del(alloc);
free(data);
return 1;
}
fprintf(stderr, "OK\n");
xj_alloc_del(alloc);
free(data);
return 0;
}
}
+44
View File
@@ -0,0 +1,44 @@
#include <string.h>
#include <stdio.h>
#include <xjson.h>
int main()
{
// Instanciate the allocator.
xj_alloc *alloc = xj_alloc_new(65536, 4096);
if(alloc == NULL)
// Handle failure maybe?
return 1;
char *str = "{\"name\": \"Francesco\", \"age\": 23}";
// Do the actual parsing..
xj_value *val = xj_decode(str, -1, alloc, NULL);
// ..error?
if(val == NULL)
fprintf(stderr, "Failed to parse!\n");
char *name;
int age;
// Now iterate over the fields to get the name
// and age.
xj_value *child = val->as_object;
while(child != NULL)
{
if(!strcmp("name", child->key))
name = child->as_string;
else
age = child->as_int;
child = child->next;
}
printf("name: %s, age: %d\n", name, age);
// Now free everything!
xj_alloc_del(alloc);
return 0;
}