| .clang-format | ||
| .clangd | ||
| create-zip.sh | ||
| json.c | ||
| json.h | ||
| readme.md | ||
Lillith's json.c
A simple JSON parser in pure C!
<500 lines excluding whitespace!
That's it! That's the library!
Here's the header file to explain how to use it:
typedef enum { // pointer contents:
JSON_INVALID, // null pointer, unused enum variant
JSON_OBJECT, // json_object
JSON_ARRAY, // json_array
JSON_STRING, // null-terminated string
JSON_NUMBER, // double
JSON_BOOL, // bool
JSON_NULL, // null pointer
} json_element_type;
typedef struct struct_json_object json_object;
typedef struct struct_json_array json_array;
typedef struct struct_json_element {
json_element_type type;
union {
json_object *object;
json_array *array;
char *string;
double *number;
bool *boolean;
void *raw;
} value;
} json_element;
typedef struct struct_json_pair {
char *key;
json_element *value;
} json_pair;
struct struct_json_object {
unsigned int size;
json_pair *values[];
};
struct struct_json_array {
unsigned int size;
json_element *values[];
};
json_element *json_parse(const char *src);
void json_dump(const json_element *element);
void json_dump_pretty(const json_element *element);
void json_free(json_element *element);
bool json_has_key(const json_element *object, const char *key);
json_element *json_get_key(const json_element *object, const char *key);
size_t curl_json_writefunction(char *src, size_t _, size_t size, void *data);
Call json_parse on your input string.
If it returns NULL, the JSON had an error somewhere in it.
Otherwise, it was valid, and you have a JSON object!
Check type to see what it was, and use the appropriate union value to cast it.
Then once you're done, call json_free on the root object you received.
If you call it on subtrees and leak memory, it's your fault not mine!
For retrieving values out of objects, there is json_has_key (to check if a key is present) and json_get_key to get the value of a key.
json_get_key will return NULL if the key is not found.
For debugging, there are json_dump and json_dump_pretty.
Former dumps without indents, latter dumps with indents.
Finally, curl_json_writefunction, as the name implies, is a writefunction for libcurl that stores its JSON output to data.
Specifically, data is treated as a json_element **.
Issues? Feature Request?
Contact me through an appropriate method on https://inx.moe
Keep in mind though, I am unlikely to implement any feature requests, as it is complete enough for my needs. It's supposed to be a simple JSON parser after all, not a complex JSON parser.