• Stars
    star
    248
  • Rank 158,236 (Top 4 %)
  • Language
    C
  • License
    The Unlicense
  • Created over 9 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

C JSON parser library that doesn't suck

Public Domain JSON Parser for C

A public domain JSON parser focused on correctness, ANSI C99 compliance, full Unicode (UTF-8) support, minimal memory footprint, and a simple API. As a streaming API, arbitrary large JSON could be processed with a small amount of memory (the size of the largest string in the JSON). It seems most C JSON libraries suck in some significant way: broken string support (what if the string contains \u0000?), broken/missing Unicode support, or crappy software license (GPL or "do no evil"). This library intends to avoid these flaws.

The parser is intended to support exactly the JSON standard, no more, no less, so that even slightly non-conforming JSON is rejected. The input is assumed to be UTF-8, and all strings returned by the library are UTF-8 with possible nul characters in the middle, which is why the size output parameter is important. Encoded characters (\uxxxx) are decoded and re-encoded into UTF-8. UTF-16 surrogate pairs expressed as adjacent encoded characters are supported.

One exception to this rule is made to support a "streaming" mode. When a JSON "stream" contains multiple JSON objects (optionally separated by JSON whitespace), the default behavior of the parser is to allow the stream to be "reset," and to continue parsing the stream.

The library is usable and nearly complete, but needs polish.

API Overview

All parser state is attached to a json_stream struct. Its fields should not be accessed directly. To initialize, it can be "opened" on an input FILE * stream or memory buffer. It's disposed of by being "closed."

void json_open_stream(json_stream *json, FILE * stream);
void json_open_string(json_stream *json, const char *string);
void json_open_buffer(json_stream *json, const void *buffer, size_t size);
void json_close(json_stream *json);

After opening a stream, custom allocator callbacks can be specified, in case allocations should not come from a system-supplied malloc. (When no custom allocator is specified, the system allocator is used.)

struct json_allocator {
    void *(*malloc)(size_t);
    void *(*realloc)(void *, size_t);
    void (*free)(void *);
};


void json_set_allocator(json_stream *json, json_allocator *a);

By default only one value is read from the stream. The parser can be reset to read more objects. The overall line number and position are preserved.

void json_reset(json_stream *json);

If strict conformance to the JSON standard is desired, streaming mode can be disabled by calling json_set_streaming and setting the mode to false. This will cause any non-whitespace trailing data to trigger a parse error.

void json_set_streaming(json_stream *json, bool mode);

The JSON is parsed as a stream of events (enum json_type). The stream is in the indicated state, during which data can be queried and retrieved.

enum json_type json_next(json_stream *json);
enum json_type json_peek(json_stream *json);

const char *json_get_string(json_stream *json, size_t *length);
double json_get_number(json_stream *json);

Numbers can also be retrieved by json_get_string(), which will return the raw text number as it appeared in the JSON. This is useful if better precision is required.

In the case of a parse error, the event will be JSON_ERROR. The stream cannot be used again until it is reset. In the event of an error, a human-friendly, English error message is available, as well as the line number and byte position. (The line number and byte position are always available.)

const char *json_get_error(json_stream *json);
size_t json_get_lineno(json_stream *json);
size_t json_get_position(json_stream *json);

Outside of errors, a JSON_OBJECT event will always be followed by zero or more pairs of JSON_STRING (member name) events and their associated value events. That is, the stream of events will always be logical and consistent.

In the streaming mode the end of the input is indicated by returning a second JSON_DONE event. Note also that in this mode an input consisting of zero JSON values is valid and is represented by a single JSON_DONE event.

JSON values in the stream can be separated by zero or more JSON whitespaces. Stricter or alternative separation can be implemented by reading and analyzing characters between values using the following functions.

int json_source_get (json_stream *json);
int json_source_peek (json_stream *json);
bool json_isspace(int c);

As an example, the following code fragment makes sure values are separated by at least one newline.

enum json_type e = json_next(json);

if (e == JSON_DONE) {
    int c = '\0';
    while (json_isspace(c = json_source_peek(json))) {
        json_source_get(json);
        if (c == '\n')
            break;
    }

    if (c != '\n' && c != EOF) {
        /* error */
    }

    json_reset(json);
}

More Repositories

1

endlessh

SSH tarpit that slowly sends an endless banner
C
6,762
star
2

w64devkit

Portable C and C++ Development Kit for x64 (and x86) Windows
C
2,216
star
3

elfeed

An Emacs web feeds client
Emacs Lisp
1,371
star
4

skewer-mode

Live web development in Emacs
Emacs Lisp
1,066
star
5

enchive

Encrypted personal archives
C
617
star
6

branchless-utf8

Branchless UTF-8 decoder
C
568
star
7

hash-prospector

Automated integer hash function discovery
C
425
star
8

pixelcity

Shamus Young's procedural city project
C++
359
star
9

scratch

Personal scratch code
C
327
star
10

optparse

Portable, reentrant, getopt-like option parser
C
308
star
11

interactive-c-demo

Demonstration of interactive C programming
C
247
star
12

emacs-aio

async/await for Emacs Lisp
Emacs Lisp
214
star
13

webgl-particles

WebGL particle system demo
JavaScript
203
star
14

fantasyname

Fantasy name generator
C
180
star
15

lstack

C11 Lock-free Stack
C
172
star
16

resurrect-js

JavaScript serialization that preserves behavior and reference circularity.
JavaScript
169
star
17

passphrase2pgp

Generate a PGP key from a passphrase
Go
168
star
18

pure-linux-threads-demo

Pthreads-free Linux threading demo
Assembly
135
star
19

memdig

Memory cheat tool for Windows and Linux games
C
130
star
20

ptrace-examples

Examples for Linux ptrace(2)
C
127
star
21

dosdefender-ld31

DOS Defender (Ludum Dare #31)
C
125
star
22

dotfiles

My personal dotfiles
Shell
124
star
23

Prelude-of-the-Chambered

Notch's Prelude of the Chambered 48-hour game
Java
124
star
24

sort-circle

Colorful sorting animations
C
121
star
25

.emacs.d

My personal .emacs.d
Emacs Lisp
119
star
26

growable-buf

Growable Memory Buffer for C99
C
113
star
27

youtube-dl-emacs

Emacs youtube-dl download manager
Emacs Lisp
103
star
28

opengl-demo

Minimal OpenGL 3.3 core profile demo
C
97
star
29

getopt

POSIX getopt() as a portable header library
C
96
star
30

Minicraft

Notch's Ludum Dare 22 entry.
Java
95
star
31

igloojs

Low-level, fluent, OOP WebGL wrapper
JavaScript
89
star
32

webgl-game-of-life

WebGL Game of Life
JavaScript
88
star
33

trie

C99 trie library
C
86
star
34

hastyhex

A blazing fast hex dumper
C
85
star
35

elisp-ffi

Emacs Lisp Foreign Function Interface
C++
83
star
36

bmp

24-bit BMP (Bitmap) ANSI C header library
C
82
star
37

rng-js

JavaScript seedable random number generation tools.
JavaScript
82
star
38

mandel-simd

Mandelbrot set in SIMD (SSE, AVX)
C
81
star
39

sample-java-project

Example Ant-based Java project
Java
78
star
40

nasm-mode

Major mode for editing NASM assembly programs
Emacs Lisp
76
star
41

vulkan-test

Test if your system supports Vulkan
C
72
star
42

u-config

a smaller, simpler, portable pkg-config clone
C
71
star
43

at-el

Prototype-based Emacs Lisp object system
Emacs Lisp
71
star
44

gap-buffer-animator

Gap buffer animation creator
C
71
star
45

skeeto.github.com

Personal website/blog
HTML
64
star
46

ulid-c

ULID Library for C
C
59
star
47

xf8

8-bit Xor Filter in C99
C
59
star
48

race64

World's fastest Base64 encoder / decoder
C
58
star
49

devdocs-lookup

Quick Emacs API lookup on devdocs.io
Emacs Lisp
58
star
50

webgl-path-solver

WebGL shortest path solver
JavaScript
57
star
51

javadoc-lookup

Quickly lookup Javadoc pages from Emacs
Emacs Lisp
55
star
52

x86-lookup

Quickly jump to x86 documentation from Emacs
Emacs Lisp
54
star
53

am-i-shadowbanned

Online reddit shadowban test
JavaScript
53
star
54

fun-liquid

Physics engine liquid in Java.
Java
53
star
55

minimail

Embeddable POP3 + SMTP server.
C
49
star
56

emacs-memoize

Elisp memoization functions
Emacs Lisp
48
star
57

simplegpg

Simplified, signify-like interface to GnuPG signatures
Shell
46
star
58

autotetris-mode

Automatically play Emacs Tetris
Emacs Lisp
45
star
59

fiber-await

Win32 Fiber async/await demo
C
44
star
60

webgl-fire

WebGL fire effect
JavaScript
43
star
61

lorenz-webgl

Lorenz System WebGL
JavaScript
42
star
62

elisp-json-rpc

JSON-RPC library for Emacs Lisp
Emacs Lisp
39
star
63

hashtab

Simple C hash table
C
37
star
64

asteroids-demo

Asteroids Clone for Windows
C
36
star
65

pgp-poisoner

PGP key poisoner
Go
36
star
66

wisp

Wisp, a lisp programming language
C
33
star
67

binitools

Bini file translator for the game Freelancer
C
32
star
68

bf-x86

x86_64 brainfuck compiler
C
32
star
69

double-pendulum

JavaScript double pendulum simulation with RK4 integration
JavaScript
30
star
70

purgeable

Purgeable memory allocations for Linux
C
29
star
71

predd

Multimethods for Emacs Lisp
Emacs Lisp
29
star
72

atomkv

In-memory, JSON, key-value service with compare-and-swap updates and event streams
Go
27
star
73

goblin-com

Goblin-COM roguelike game for 7DRL 2015
C
27
star
74

lqueue

C11 + Pthreads Atomic Bounded Work Queue
C
27
star
75

jekyll-deck

Template for Jekyll / deck.js presentations
27
star
76

uuid

UUID generator for Go
Go
26
star
77

rlhk

Roguelike Header Kit
C
26
star
78

voronoi-toy

WebGL interactive Voronoi diagram
JavaScript
26
star
79

transcription-mode

Emacs mode for editing transcripts.
Emacs Lisp
25
star
80

october-chess-engine

Java Chess Engine
Java
25
star
81

boids-js

HTML5 boids (skewer-mode demo)
JavaScript
25
star
82

geohash

Fast, lean, efficient geohash C library
C
24
star
83

bitpack

Emacs Lisp structure packing
Emacs Lisp
23
star
84

connect4

Connect Four AI and Engine
C
22
star
85

lean-static-gpg

Lean, static GnuPG build for Linux
Shell
22
star
86

blowpipe

Authenticated Blowfish-encrypted pipe
C
22
star
87

markov-text

Markov chain text generation in Emacs Lisp
Emacs Lisp
22
star
88

joymacs

Joystick support for Emacs
C
21
star
89

optparse-go

GNU style long options for Go
Go
21
star
90

emacs-rsa

RSA cryptography in Emacs Lisp
Emacs Lisp
20
star
91

live-dev-env

A live CD of my personal development environment
Shell
20
star
92

dynamic-function-benchmark

Benchmark for three different kinds of dynamic function calls
C
19
star
93

utf-7

UTF-7 encoder and decoder in ANSI C
C
18
star
94

elisp-fakespace

Emacs Lisp namespaces (defpackage)
Emacs Lisp
18
star
95

siphash

Incremental SipHash in C
C
18
star
96

bencode-c

Bencode decoder in ANSI C
C
17
star
97

british-square

British Square Engine (Analysis and Perfect AI Player)
C
17
star
98

xxtea

100% XXTEA authenticated, chunked file encryption
C
17
star
99

gnupg-windows-build

Cross-compile GnuPG for Windows using Docker
Dockerfile
17
star
100

pokerware

Pokerware Secure Passphrase Generation
Makefile
16
star