Debian Codegraph @

README.md

raw symbols SCIP
1 [![Go Report Card](https://goreportcard.com/badge/github.com/buger/jsonparser)](https://goreportcard.com/report/github.com/buger/jsonparser) ![License](https://img.shields.io/dub/l/vibe-d.svg)
2 # Alternative JSON parser for Go (10x times faster standard library)
3
4 It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **10 times faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
5
6 ## Rationale
7 Originally I made this for a project that relies on a lot of 3rd party APIs that can be unpredictable and complex.
8 I love simplicity and prefer to avoid external dependecies. `encoding/json` requires you to know exactly your data structures, or if you prefer to use `map[string]interface{}` instead, it will be very slow and hard to manage.
9 I investigated what's on the market and found that most libraries are just wrappers around `encoding/json`, there is few options with own parsers (`ffjson`, `easyjson`), but they still requires you to create data structures.
10
11
12 Goal of this project is to push JSON parser to the performance limits and not sacrifice with compliance and developer user experience.
13
14 ## Example
15 For the given JSON our goal is to extract the user's full name, number of github followers and avatar.
16
17 ```go
18 import "github.com/buger/jsonparser"
19
20 ...
21
22 data := []byte(`{
23 "person": {
24 "name": {
25 "first": "Leonid",
26 "last": "Bugaev",
27 "fullName": "Leonid Bugaev"
28 },
29 "github": {
30 "handle": "buger",
31 "followers": 109
32 },
33 "avatars": [
34 { "url": "https://avatars1.githubusercontent.com/u/14009?v=3&s=460", "type": "thumbnail" }
35 ]
36 },
37 "company": {
38 "name": "Acme"
39 }
40 }`)
41
42 // You can specify key path by providing arguments to Get function
43 jsonparser.Get(data, "person", "name", "fullName")
44
45 // There is `GetInt` and `GetBoolean` helpers if you exactly know key data type
46 jsonparser.GetInt(data, "person", "github", "followers")
47
48 // When you try to get object, it will return you []byte slice pointer to data containing it
49 // In `company` it will be `{"name": "Acme"}`
50 jsonparser.Get(data, "company")
51
52 // If the key doesn't exist it will throw an error
53 var size int64
54 if value, err := jsonparser.GetInt(data, "company", "size"); err == nil {
55 size = value
56 }
57
58 // You can use `ArrayEach` helper to iterate items [item1, item2 .... itemN]
59 jsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
60 fmt.Println(jsonparser.Get(value, "url"))
61 }, "person", "avatars")
62
63 // Or use can access fields by index!
64 jsonparser.GetString(data, "person", "avatars", "[0]", "url")
65
66 // You can use `ObjectEach` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN }
67 jsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
68 fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType)
69 return nil
70 }, "person", "name")
71
72 // The most efficient way to extract multiple keys is `EachKey`
73
74 paths := [][]string{
75 []string{"person", "name", "fullName"},
76 []string{"person", "avatars", "[0]", "url"},
77 []string{"company", "url"},
78 }
79 jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, err error){
80 switch idx {
81 case 0: // []string{"person", "name", "fullName"}
82 ...
83 case 1: // []string{"person", "avatars", "[0]", "url"}
84 ...
85 case 2: // []string{"company", "url"},
86 ...
87 }
88 }, paths...)
89
90 // For more information see docs below
91 ```
92
93 ## Reference
94
95 Library API is really simple. You just need the `Get` method to perform any operation. The rest is just helpers around it.
96
97 You also can view API at [godoc.org](https://godoc.org/github.com/buger/jsonparser)
98
99
100 ### **`Get`**
101 ```go
102 func Get(data []byte, keys ...string) (value []byte, dataType jsonparser.ValueType, offset int, err error)
103 ```
104 Receives data structure, and key path to extract value from.
105
106 Returns:
107 * `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error
108 * `dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null`
109 * `offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper.
110 * `err` - If the key is not found or any other parsing issue, it should return error. If key not found it also sets `dataType` to `NotExist`
111
112 Accepts multiple keys to specify path to JSON value (in case of quering nested structures).
113 If no keys are provided it will try to extract the closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation.
114
115 Note that keys can be an array indexes: `jsonparser.GetInt("person", "avatars", "[0]", "url")`, pretty cool, yeah?
116
117 ### **`GetString`**
118 ```go
119 func GetString(data []byte, keys ...string) (val string, err error)
120 ```
121 Returns strings properly handing escaped and unicode characters. Note that this will cause additional memory allocations.
122
123 ### **`GetUnsafeString`**
124 If you need string in your app, and ready to sacrifice with support of escaped symbols in favor of speed. It returns string mapped to existing byte slice memory, without any allocations:
125 ```go
126 s, _, := jsonparser.GetUnsafeString(data, "person", "name", "title")
127 switch s {
128 case 'CEO':
129 ...
130 case 'Engineer'
131 ...
132 ...
133 }
134 ```
135 Note that `unsafe` here means that your string will exist until GC will free underlying byte slice, for most of cases it means that you can use this string only in current context, and should not pass it anywhere externally: through channels or any other way.
136
137
138 ### **`GetBoolean`**, **`GetInt`** and **`GetFloat`**
139 ```go
140 func GetBoolean(data []byte, keys ...string) (val bool, err error)
141
142 func GetFloat(data []byte, keys ...string) (val float64, err error)
143
144 func GetInt(data []byte, keys ...string) (val int64, err error)
145 ```
146 If you know the key type, you can use the helpers above.
147 If key data type do not match, it will return error.
148
149 ### **`ArrayEach`**
150 ```go
151 func ArrayEach(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string)
152 ```
153 Needed for iterating arrays, accepts a callback function with the same return arguments as `Get`.
154
155 ### **`ObjectEach`**
156 ```go
157 func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
158 ```
159 Needed for iterating object, accepts a callback function. Example:
160 ```go
161 var handler func([]byte, []byte, jsonparser.ValueType, int) error
162 handler = func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {
163 //do stuff here
164 }
165 jsonparser.ObjectEach(myJson, handler)
166 ```
167
168
169 ### **`EachKey`**
170 ```go
171 func EachKey(data []byte, cb func(idx int, value []byte, dataType jsonparser.ValueType, err error), paths ...[]string)
172 ```
173 When you need to read multiple keys, and you do not afraid of low-level API `EachKey` is your friend. It read payload only single time, and calls callback function once path is found. For example when you call multiple times `Get`, it has to process payload multiple times, each time you call it. Depending on payload `EachKey` can be multiple times faster than `Get`. Path can use nested keys as well!
174
175 ```go
176 paths := [][]string{
177 []string{"uuid"},
178 []string{"tz"},
179 []string{"ua"},
180 []string{"st"},
181 }
182 var data SmallPayload
183
184 jsonparser.EachKey(smallFixture, func(idx int, value []byte, vt jsonparser.ValueType, err error){
185 switch idx {
186 case 0:
187 data.Uuid, _ = value
188 case 1:
189 v, _ := jsonparser.ParseInt(value)
190 data.Tz = int(v)
191 case 2:
192 data.Ua, _ = value
193 case 3:
194 v, _ := jsonparser.ParseInt(value)
195 data.St = int(v)
196 }
197 }, paths...)
198 ```
199
200 ### **`Set`**
201 ```go
202 func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error)
203 ```
204 Receives existing data structure, key path to set, and value to set at that key. *This functionality is experimental.*
205
206 Returns:
207 * `value` - Pointer to original data structure with updated or added key value.
208 * `err` - If any parsing issue, it should return error.
209
210 Accepts multiple keys to specify path to JSON value (in case of updating or creating nested structures).
211
212 Note that keys can be an array indexes: `jsonparser.Set(data, []byte("http://github.com"), "person", "avatars", "[0]", "url")`
213
214 ### **`Delete`**
215 ```go
216 func Delete(data []byte, keys ...string) value []byte
217 ```
218 Receives existing data structure, and key path to delete. *This functionality is experimental.*
219
220 Returns:
221 * `value` - Pointer to original data structure with key path deleted if it can be found. If there is no key path, then the whole data structure is deleted.
222
223 Accepts multiple keys to specify path to JSON value (in case of updating or creating nested structures).
224
225 Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avatars", "[0]", "url")`
226
227
228 ## What makes it so fast?
229 * It does not rely on `encoding/json`, `reflection` or `interface{}`, the only real package dependency is `bytes`.
230 * Operates with JSON payload on byte level, providing you pointers to the original data structure: no memory allocation.
231 * No automatic type conversions, by default everything is a []byte, but it provides you value type, so you can convert by yourself (there is few helpers included).
232 * Does not parse full record, only keys you specified
233
234
235 ## Benchmarks
236
237 There are 3 benchmark types, trying to simulate real-life usage for small, medium and large JSON payloads.
238 For each metric, the lower value is better. Time/op is in nanoseconds. Values better than standard encoding/json marked as bold text.
239 Benchmarks run on standard Linode 1024 box.
240
241 Compared libraries:
242 * https://golang.org/pkg/encoding/json
243 * https://github.com/Jeffail/gabs
244 * https://github.com/a8m/djson
245 * https://github.com/bitly/go-simplejson
246 * https://github.com/antonholmquist/jason
247 * https://github.com/mreiferson/go-ujson
248 * https://github.com/ugorji/go/codec
249 * https://github.com/pquerna/ffjson
250 * https://github.com/mailru/easyjson
251 * https://github.com/buger/jsonparser
252
253 #### TLDR
254 If you want to skip next sections we have 2 winner: `jsonparser` and `easyjson`.
255 `jsonparser` is up to 10 times faster than standard `encoding/json` package (depending on payload size and usage), and almost infinitely (literally) better in memory consumption because it operates with data on byte level, and provide direct slice pointers.
256 `easyjson` wins in CPU in medium tests and frankly i'm impressed with this package: it is remarkable results considering that it is almost drop-in replacement for `encoding/json` (require some code generation).
257
258 It's hard to fully compare `jsonparser` and `easyjson` (or `ffson`), they a true parsers and fully process record, unlike `jsonparser` which parse only keys you specified.
259
260 If you searching for replacement of `encoding/json` while keeping structs, `easyjson` is an amazing choice. If you want to process dynamic JSON, have memory constrains, or more control over your data you should try `jsonparser`.
261
262 `jsonparser` performance heavily depends on usage, and it works best when you do not need to process full record, only some keys. The more calls you need to make, the slower it will be, in contrast `easyjson` (or `ffjson`, `encoding/json`) parser record only 1 time, and then you can make as many calls as you want.
263
264 With great power comes great responsibility! :)
265
266
267 #### Small payload
268
269 Each test processes 190 bytes of http log as a JSON record.
270 It should read multiple fields.
271 https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payload_test.go
272
273 Library | time/op | bytes/op | allocs/op
274 ------ | ------- | -------- | -------
275 encoding/json struct | 7879 | 880 | 18
276 encoding/json interface{} | 8946 | 1521 | 38
277 Jeffail/gabs | 10053 | 1649 | 46
278 bitly/go-simplejson | 10128 | 2241 | 36
279 antonholmquist/jason | 27152 | 7237 | 101
280 github.com/ugorji/go/codec | 8806 | 2176 | 31
281 mreiferson/go-ujson | **7008** | **1409** | 37
282 a8m/djson | 3862 | 1249 | 30
283 pquerna/ffjson | **3769** | **624** | **15**
284 mailru/easyjson | **2002** | **192** | **9**
285 buger/jsonparser | **1367** | **0** | **0**
286 buger/jsonparser (EachKey API) | **809** | **0** | **0**
287
288 Winners are ffjson, easyjson and jsonparser, where jsonparser is up to 9.8x faster than encoding/json and 4.6x faster than ffjson, and slightly faster than easyjson.
289 If you look at memory allocation, jsonparser has no rivals, as it makes no data copy and operates with raw []byte structures and pointers to it.
290
291 #### Medium payload
292
293 Each test processes a 2.4kb JSON record (based on Clearbit API).
294 It should read multiple nested fields and 1 array.
295
296 https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_payload_test.go
297
298 | Library | time/op | bytes/op | allocs/op |
299 | ------- | ------- | -------- | --------- |
300 | encoding/json struct | 57749 | 1336 | 29 |
301 | encoding/json interface{} | 79297 | 10627 | 215 |
302 | Jeffail/gabs | 83807 | 11202 | 235 |
303 | bitly/go-simplejson | 88187 | 17187 | 220 |
304 | antonholmquist/jason | 94099 | 19013 | 247 |
305 | github.com/ugorji/go/codec | 114719 | 6712 | 152 |
306 | mreiferson/go-ujson | **56972** | 11547 | 270 |
307 | a8m/djson | 28525 | 10196 | 198 |
308 | pquerna/ffjson | **20298** | **856** | **20** |
309 | mailru/easyjson | **10512** | **336** | **12** |
310 | buger/jsonparser | **15955** | **0** | **0** |
311 | buger/jsonparser (EachKey API) | **8916** | **0** | **0** |
312
313 The difference between ffjson and jsonparser in CPU usage is smaller, while the memory consumption difference is growing. On the other hand `easyjson` shows remarkable performance for medium payload.
314
315 `gabs`, `go-simplejson` and `jason` are based on encoding/json and map[string]interface{} and actually only helpers for unstructured JSON, their performance correlate with `encoding/json interface{}`, and they will skip next round.
316 `go-ujson` while have its own parser, shows same performance as `encoding/json`, also skips next round. Same situation with `ugorji/go/codec`, but it showed unexpectedly bad performance for complex payloads.
317
318
319 #### Large payload
320
321 Each test processes a 24kb JSON record (based on Discourse API)
322 It should read 2 arrays, and for each item in array get a few fields.
323 Basically it means processing a full JSON file.
324
325 https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payload_test.go
326
327 | Library | time/op | bytes/op | allocs/op |
328 | --- | --- | --- | --- |
329 | encoding/json struct | 748336 | 8272 | 307 |
330 | encoding/json interface{} | 1224271 | 215425 | 3395 |
331 | a8m/djson | 510082 | 213682 | 2845 |
332 | pquerna/ffjson | **312271** | **7792** | **298** |
333 | mailru/easyjson | **154186** | **6992** | **288** |
334 | buger/jsonparser | **85308** | **0** | **0** |
335
336 `jsonparser` now is a winner, but do not forget that it is way more lightweight parser than `ffson` or `easyjson`, and they have to parser all the data, while `jsonparser` parse only what you need. All `ffjson`, `easysjon` and `jsonparser` have their own parsing code, and does not depend on `encoding/json` or `interface{}`, thats one of the reasons why they are so fast. `easyjson` also use a bit of `unsafe` package to reduce memory consuption (in theory it can lead to some unexpected GC issue, but i did not tested enough)
337
338 Also last benchmark did not included `EachKey` test, because in this particular case we need to read lot of Array values, and using `ArrayEach` is more efficient.
339
340 ## Formal Verification
341
342 <!-- Documents: SYS-REQ-001, SYS-REQ-016, SYS-REQ-017, SYS-REQ-018, SYS-REQ-019, SYS-REQ-020, SYS-REQ-021, SYS-REQ-022, SYS-REQ-023, SYS-REQ-024, SYS-REQ-025, SYS-REQ-026, SYS-REQ-027 -->
343
344 This project uses [ReqProof](https://reqproof.com) for formal requirements verification, achieving:
345
346 - **92 formally specified requirements** covering all public API behavior including edge cases, malformed input, boundary values, and error propagation
347 - **100% MC/DC coverage** (Modified Condition/Decision Coverage) — every boolean decision in the code is independently proven exercised
348 - **Kind2 model checking** — mathematical proof that the specification is realizable and consistent
349 - **Z3 SMT proofs** — data-level properties verified for all possible inputs, not just test samples
350
351 ReqProof found **2 real bugs** during the verification process ([see PR #281](https://github.com/buger/jsonparser/pull/281)):
352 1. `Delete` panic on truncated JSON input — bounds check missing after internal sentinel value
353 2. `ArrayEach` callback silently swallowing parse errors — the callback's `err` parameter was always nil
354
355 It also identified and safely removed **7 dead code blocks** that MC/DC analysis proved unreachable from any input.
356
357 The verification runs on every PR via [probelabs/proof-action](https://github.com/probelabs/proof-action).
358
359 ## Questions and support
360
361 All bug-reports and suggestions should go though Github Issues.
362
363 ## Contributing
364
365 1. Fork it
366 2. Create your feature branch (git checkout -b my-new-feature)
367 3. Commit your changes (git commit -am 'Added some feature')
368 4. Push to the branch (git push origin my-new-feature)
369 5. Create new Pull Request
370
371 ## Development
372
373 All my development happens using Docker, and repo include some Make tasks to simplify development.
374
375 * `make build` - builds docker image, usually can be called only once
376 * `make test` - run tests
377 * `make fmt` - run go fmt
378 * `make bench` - run benchmarks (if you need to run only single benchmark modify `BENCHMARK` variable in make file)
379 * `make profile` - runs benchmark and generate 3 files- `cpu.out`, `mem.mprof` and `benchmark.test` binary, which can be used for `go tool pprof`
380 * `make bash` - enter container (i use it for running `go tool pprof` above)