An open API service indexing awesome lists of open source software.

https://github.com/sebbekarlsson/libjson

Simple C implementation of JSON, parse JSON in C.
https://github.com/sebbekarlsson/libjson

clang json json-parser lexer parser serialization

Last synced: 6 months ago
JSON representation

Simple C implementation of JSON, parse JSON in C.

Awesome Lists containing this project

README

          

# libjson
> Super fast JSON implementation in C, parse JSON in C with the speed of light.

## Usage
> To parse json in C, here is an example.
> Let's say we have a json file called **person.json**:
```json
{
"age": 32,
"name": "John Doe",
"email": "doe@doecompany.com"
}
```
> ... and we want to parse it,
> and read the `name` field:
```C
#include

int main(int argc, char* argv[])
{
// load the parser with the file
json_parser_T* parser = init_json_parser(init_json_lexer(read_file("shards/person.json")));

// parse the file
json_ast_T* ast = json_parser_parse(parser);

// look for the key we are interested in
for (int i = 0; i < ast->key_value_list_size; i++)
{
json_ast_T* key_value = ast->key_value_list_value[i];

if (strcmp(key_value->key_value_key, "name") == 0)
{
// print it
printf("The name is: `%s`\n", key_value->key_value_value->string_value);

// we were only interested in the name, so let's just break.
break;
}
}

// don't forget to free some memory.
json_parser_free(parser);
json_ast_free(ast);
}
```
> Compile your project with the `-ljson` flag:
```bash
gcc -ljson main.c
```

## Installing
> To install `libjson`, simply clown down the repo and run:
```
make && sudo make install
```
> Done! Now you can use it.

## Speed
> The parser parses the [shards/boards.json](shards/boards.json) file in about
> `0.002` seconds:
```bash
time ./a.out

real 0m0.002s
user 0m0.003s
sys 0m0.000s
```
> Parsing the same file in `Nodejs` takes this much time:
```bash
time node n.js

real 0m0.412s
user 0m0.402s
sys 0m0.012s
```
> Parsing the same file in `Python` takes this much time:
```bash
time python n.py

real 0m0.016s
user 0m0.004s
sys 0m0.012s
```
> Conclusion: __My parser wins!__.

## Valgrind output
> Here is the valgrind output after parsing [shards/boards.json](shards/boards.json):
```
==24912== HEAP SUMMARY:
==24912== in use at exit: 0 bytes in 0 blocks
==24912== total heap usage: 73,145 allocs, 73,145 frees, 118,651,826 bytes allocated
==24912==
==24912== All heap blocks were freed -- no leaks are possible
==24912==
==24912== For counts of detected and suppressed errors, rerun with: -v
==24912== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```
> No memory leaks, no errors! All good.