Sj.h: a Tiny Little JSON Parsing Library in ~150 Lines of C99
Posted3 months agoActive3 months ago
github.comTechstoryHigh profile
calmmixed
Debate
60/100
JSON ParsingC ProgrammingEmbedded Systems
Key topics
JSON Parsing
C Programming
Embedded Systems
A tiny JSON parsing library in C99 is shared, sparking discussion on its simplicity, limitations, and potential use cases.
Snapshot generated from the HN discussion
Discussion Activity
Very active discussionFirst comment
22m
Peak period
50
0-3h
Avg / period
14.5
Comment distribution160 data points
Loading chart...
Based on 160 loaded comments
Key moments
- 01Story posted
Sep 21, 2025 at 12:43 PM EDT
3 months ago
Step 01 - 02First comment
Sep 21, 2025 at 1:05 PM EDT
22m after posting
Step 02 - 03Peak activity
50 comments in 0-3h
Hottest window of the conversation
Step 03 - 04Latest activity
Sep 23, 2025 at 11:18 AM EDT
3 months ago
Step 04
Generating AI Summary...
Analyzing up to 500 comments to identify key contributors and discussion patterns
ID: 45324349Type: storyLast synced: 11/20/2025, 8:23:06 PM
Want the full context?
Jump to the original sources
Read the primary article or dive into the live Hacker News thread when you're ready.
https://github.com/nst/JSONTestSuite
The nesting is limited by using an int as the depth counter. The C standard guarantees that MAX_INT is at least 32767, so that’s a limit on portable nesting depth. Nowadays int is typically 32 or 64 bits, so a much higher limit in typical C implementations.
If I see correctly, the library doesn’t check for overflow, however. This might conceivably be an exploitable vulnerability (and such an overflow would constitute UB).
What I mean by this is a subset (superset?) that exactly matches the parsing behavior of a specific target parsing library. Why is this useful? To avoid the class of vulnerabilities that rely on the same JSON being handled differently by two different parsers (you can exploit this to get around an authorization layer, for example).
Also, license compliance is very easy (no notice required).
- log.c - A simple logging library implemented in C99
- microui - A tiny immediate-mode UI library
- fe - A tiny, embeddable language implemented in ANSI C
- microtar - A lightweight tar library written in ANSI C
- cembed - A small utility for embedding files in a C header
- ini - A tiny ANSI C library for loading .ini config files
- json.lua - A lightweight JSON library for Lua
- lite - A lightweight text editor written in Lua
- cmixer - Portable ANSI C audio mixer for games
- uuid4 - A tiny C library for generating uuid4 strings
Edit: I was not aware of the FSF's definition. I was using a definition of free software being software that you can use without having to pay for it.
Depends on which "free software" definition you're referring to.
The FSF definition of "free software" requires it to be open source.
[1] https://spdx.org/licenses/
That’s called freeware. Also, open-source software can be paid (with the caveat that if someone buys it, you must allow them to redistribute it for free).
To add an additional suggestion, gratis can also be used to refer to free as in free beer. Comes from a latin root and is common in spanish speaking countries to refer only to free of charge, and not as in freedom.
So I have much more trust in (A)GPL licensed projects, and I see them as more for the people than MIT licensed projects.
People != the legal departments of corporations.
lol
They care more about the package being maintained, bug-free, and their preferred vulnerability database showing no active exploits.
At least in my experience, anyway. Other companies may have stricter requirements.
SQLite on the other hand just says
which seems less useful once you strike sentence 1.[1] https://www.gnu.org/philosophy/free-sw.html [2] https://opensource.org/osd
> not free software
which it is. As F3nd0 said, it's both.
The MIT license upholds the four essential freedoms of free software: the right to run, copy, distribute, study, change and improve the software.
It is listed under "Expat License" in the list of GPL-compatible Free Software licenses.
https://www.gnu.org/licenses/license-list.html
I used "lite" (text editor in Lua) which has been mentioned under this submission. It is cool, too.
https://github.com/rxi/lume
They're either written with a different use case in mind, or a complex mess of abstractions; often both.
It's not a very difficult problem to solve if you only write exactly what you need for your specific use case.
Anyhow, IMO a proper JSON library should offer both, in a layered approach. That is, a lower level SAX-style parser, on top of which a DOM-style API is provided as a convenience.
Not really because the JSON library itself can stream the input. For example if you use `serde_json::from_reader()` it won't load the whole file into memory before parsing it into your objects:
https://docs.rs/serde_json/latest/serde_json/fn.from_reader....
But that's kind of academic; half of all memory and all memory are in the same league.
The once "very simple" C++ single-header JSON library by nlohmann is now
* 13 years old
* is still actively merging PRs (last one 5 hours ago)
* has 122 __million__ unit tests
Despite all this, it's self-admittedly still not the fastest possible way to parse JSON in C++. For that you might want to look into simdjson.
Don't start your own JSON parser library. Just don't. Yes you can whiteboard one that's 90% good enough in 45 minutes but that last 10% takes ten thousand man hours.
https://github.com/kstenerud/KSCrash/blob/master/Sources/KSC...
And yeah, writing a JSON codec sucks.
So I'm in the process of replacing it with a BONJSON codec, which has the same capabilities, is still async-safe and crash resilient, and is 35x faster with less code.
https://github.com/kstenerud/ksbonjson/blob/main/library/src...
https://github.com/kstenerud/ksbonjson/blob/main/library/src...
That's the thing with reinventing wheels, a wheel that fits every possible vehicle and runs well in any possible terrain is very difficult to build. But when you know exactly what you need it's a different story.
https://seriot.ch/projects/parsing_json.html
So in this case you're wrong.
General purpose is a different can of worms compared to solving a specific case.
Sexprs sitting over here, hoping for some love.
https://github.com/rxi/sj.h/blob/eb725e0858877e86932128836c1...
https://github.com/rxi/sj.h/blob/eb725e0858877e86932128836c1...
https://github.com/rxi/sj.h/blob/eb725e0858877e86932128836c1...
https://github.com/rxi/sj.h/blob/eb725e0858877e86932128836c1...
Certain inputs can therefore trigger UB.
Sometimes, it's just not the responsibility of the library. Trying to handle every possible errors is a quick way to complexity.
[0]: https://43081j.com/2025/09/bloat-of-edge-case-libraries
[1]: https://news.ycombinator.com/item?id=45319399
Code is the ultimate specification. I don't trust the docs if the behavior is different from what it's saying (or more often fails to mention). And anything that deals with recursive structures (or looping without a clear counter and checks) is my one of the first candidate for checks.
> has no way to handle the overflow case after the fact.
Fork/Vendor the code and add your assertions.
In the spirit of the article you linked, I’d rather write my own version.
Here's an example - I once coded a limited JSON parser in assembly language. I did not attempt to make it secure in any way. The purpose was to parse control messages sent over a serial port connection to an embedded CPU that controlled a small motor to rotate a camera and snap a photo. There was simply no way for any "untrusted" JSON to enter the system. It worked perfectly and nothing could ever be compromised by having a very simple JSON parser in the embedded device controlling the motor.
For this specific project I chose JSON and it worked perfectly. Sending JSON from the embedded CPU was also really simple. Yes, there was a little overhead on a slow connection, but I wasn't getting anywhere near saturation. I think it was 9600 bps max on a noisy connection with checksums. If even 10% of the JSON "packets" got through it was still plenty for the system to run.
Isn't that a bit like saying "you don't have to worry about home security as long as you are the only person who has the ability to enter your house"?
If you need it, then you need it. But if you don't need it, then you don't need it. There is a non-trivial value in the smallness and simplicity, and a non-trivial cost in trying to handle infinity problems when you don't have infinity use-case.
If you are reading data from a file or stream that only you yourself wrote some other time, then it's true that data could possibly have been corrupted or something, but it's not true that it's automatically worth worrying about enough to justify making the code and thus it's bug surface larger.
How likely is the problem, how bad are the consequences if the problem happens, how many edge cases could possibly exist, how much code does it take to handle them all? None of these are questions you or anyone else can say about anyone else's project ahead of time.
If the full featured parser is too big, then the line drawing the scope of the lightweight parser has to go somewhere, and so of course there will be things on the other side of that line no matter where it is except all the way back at full-featured-parser.
"just this one little check" is not automatially reasonable, because that check isn't automatically more impoprtant than any other, and they are all "just one little checks"s. The one little check would perevent what? Maybe a problem that never happens or doesn't hurt when it does happen. A value might be misinerpreted? So what? Let it. Maybe it makes more sense to handle that in the application code the one place it might matter. If it will matter so much, then maybe the application needs the full fat library.
Using a "tiny library" for parsing untrusted data is where the mistake is. Not in OP code.
(TIP: choose the latter)
Writing a function to do a checked addition like in other languages isn't exactly difficult, either.
Detecting these mistakes in Rust is not too difficult. In debug builds, integer overflow triggers a panic[1]. Additionally, clippy (the official linter of Rust), has a rule[2] to detect this mistake.
[1] https://doc.rust-lang.org/book/ch03-02-data-types.html#integ...
[2] https://rust-lang.github.io/rust-clippy/master/index.html#ar...
It's the wrong attitude for a JSON parser written in C, unless you like to get owned.
UB is bad.
Sometimes. In this case, where the library is a parser that is written in C. I think it is reasonable to expect the library to handle all possible inputs. Even corner cases like this which are unlikely to be encountered in common practice. This is not "bloat" it is correctness.
In C, this kind of bug is capable of being exploited. Sure, many users of this lib won't be using it in exposed cases, but sooner or later the lib will end up in some widely-used internet-facing codebase.
As others have said, the fix could be as simple as bailing once the input size exceeds 1GB. Or it could be fine-grained. Either-way the fix would not "bloat" the codebase.
And yes, I'm well aware of the single-file C library movement. I am a fan.
- a JSON file with nested values exceeding 2 billion depth
- a file with more than 2 billion lines
- a line with more than 2 billion characters
Maybe more importantly, I won’t trust the rest of the code if the author doesn’t seem to have the finite range of integer types in mind.
Restricting the input to a reasonable size is an easy workaround for sure, but this limitation isn't indicated everywhere, so anyone deciding to consume this random project into their important code wouldn't know to defend against such situation.
In a web server scenario, 2GiB of { (which would trigger two overflows) in a compressed request would require a couple hundred kilobytes to two megabytes, depending on how old your server software is.
And in the spirit of your profile text I'm quite glad for such landmines being out there to trip up those that do blindly ingest all code they can find.
80 more comments available on Hacker News