2 ms·
I once (maybe a long time ago?) made a parser for JSON by: 1. Reading the entire file into RAM. 2. Providing a `const char *get_value(const char *jstring, con
by lelanthran 2y ago
I once (maybe a long time ago?) made a parser for JSON by:
1. Reading the entire file into RAM.
2. Providing a `const char *get_value(const char *jstring, const char *path, ...)` function with a NULL-terminated parameter list that would return the position of the value of the key at the specified path.
3. Providing a `copy_value(const char *position)` function to copy the value at the specified position.
Slow? Yup!
But, it was easy and safe[1] and used absolutely minimal RAM![2]. The recursive nature of the JSON tree also allowed the caller to use a returned value from `get_value` as the `jstring` argument in further calls to `get_value`.
I might still have a fork of it lying around somewhere.
[1] "Safe" meaning "Caller had to check for NULL return values, and ensure that NULL terminated the parameter list".
[2] GCC with `-O2` and above does proper TCO, eliminating unbounded stack growth.
- kukkamario 2y agoBetter option would be to parse json into Bson and then use that as the in-memory format. It uses minimal memory and is actually also fast to access without parsing into some other data structure.
- lelanthran 2y agoTBH I didn't know about Bson (Binary-json?). All I had was a tiny little device that rxed JSON and needed to retrieve values from the tree.
- nwpierce 2y agoThat sounds a little like what I came up with a little while back. My lib can stream JSON to/from my own compact binary format that is easy to traverse/emit in C: https://github.com/nwpierce/jsb/ https://github.com/nwpierce/jsb/
- ivanjermakov 2y agoOnly safe and easy if json file fits into the RAM.
- lelanthran 2y ago> Only safe and easy if json file fits into the RAM. So? Many of the other JSON parsing tools build up a tree in RAM[1], so the statement "Only works if the final tree fits in RAM" is just as true, and since JSON is mostly text, the final tree is not that much smaller than the source JSON anyway. [1] Including the one this article is presenting, and all the other solutions presented in the comments.
- eska 2y agoThat’s not a parser though. For example the caller would still need to convert escaped unicode characters, floats and bool. I guess it’s an incomplete tokenizer?