{"id":13492553,"url":"https://github.com/buger/jsonparser","last_synced_at":"2025-05-13T21:03:15.064Z","repository":{"id":37431569,"uuid":"54303805","full_name":"buger/jsonparser","owner":"buger","description":"One of the fastest alternative JSON parser for Go that does not require schema","archived":false,"fork":false,"pushed_at":"2024-07-12T16:56:54.000Z","size":343,"stargazers_count":5530,"open_issues_count":69,"forks_count":434,"subscribers_count":99,"default_branch":"master","last_synced_at":"2025-05-06T20:20:40.345Z","etag":null,"topics":["go","json","json-parser","parser","perfomance"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/buger.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-03-20T06:22:33.000Z","updated_at":"2025-05-04T10:43:24.000Z","dependencies_parsed_at":"2024-09-17T00:27:48.972Z","dependency_job_id":"db5e8f44-8210-41ce-ab6e-4a0feb52ba50","html_url":"https://github.com/buger/jsonparser","commit_stats":{"total_commits":201,"total_committers":52,"mean_commits":"3.8653846153846154","dds":0.5572139303482587,"last_synced_commit":"61b32cfdfa0f5d368ef7c7daef28ce12d538740f"},"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buger%2Fjsonparser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buger%2Fjsonparser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buger%2Fjsonparser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/buger%2Fjsonparser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/buger","download_url":"https://codeload.github.com/buger/jsonparser/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254027667,"owners_count":22002090,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["go","json","json-parser","parser","perfomance"],"created_at":"2024-07-31T19:01:07.035Z","updated_at":"2025-05-13T21:03:15.040Z","avatar_url":"https://github.com/buger.png","language":"Go","readme":"[![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)\n# Alternative JSON parser for Go (10x times faster standard library)\n\nIt 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.\n\n## Rationale\nOriginally I made this for a project that relies on a lot of 3rd party APIs that can be unpredictable and complex.\nI 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.\nI 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.\n\n\nGoal of this project is to push JSON parser to the performance limits and not sacrifice with compliance and developer user experience.\n\n## Example\nFor the given JSON our goal is to extract the user's full name, number of github followers and avatar.\n\n```go\nimport \"github.com/buger/jsonparser\"\n\n...\n\ndata := []byte(`{\n  \"person\": {\n    \"name\": {\n      \"first\": \"Leonid\",\n      \"last\": \"Bugaev\",\n      \"fullName\": \"Leonid Bugaev\"\n    },\n    \"github\": {\n      \"handle\": \"buger\",\n      \"followers\": 109\n    },\n    \"avatars\": [\n      { \"url\": \"https://avatars1.githubusercontent.com/u/14009?v=3\u0026s=460\", \"type\": \"thumbnail\" }\n    ]\n  },\n  \"company\": {\n    \"name\": \"Acme\"\n  }\n}`)\n\n// You can specify key path by providing arguments to Get function\njsonparser.Get(data, \"person\", \"name\", \"fullName\")\n\n// There is `GetInt` and `GetBoolean` helpers if you exactly know key data type\njsonparser.GetInt(data, \"person\", \"github\", \"followers\")\n\n// When you try to get object, it will return you []byte slice pointer to data containing it\n// In `company` it will be `{\"name\": \"Acme\"}`\njsonparser.Get(data, \"company\")\n\n// If the key doesn't exist it will throw an error\nvar size int64\nif value, err := jsonparser.GetInt(data, \"company\", \"size\"); err == nil {\n  size = value\n}\n\n// You can use `ArrayEach` helper to iterate items [item1, item2 .... itemN]\njsonparser.ArrayEach(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {\n\tfmt.Println(jsonparser.Get(value, \"url\"))\n}, \"person\", \"avatars\")\n\n// Or use can access fields by index!\njsonparser.GetString(data, \"person\", \"avatars\", \"[0]\", \"url\")\n\n// You can use `ObjectEach` helper to iterate objects { \"key1\":object1, \"key2\":object2, .... \"keyN\":objectN }\njsonparser.ObjectEach(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {\n        fmt.Printf(\"Key: '%s'\\n Value: '%s'\\n Type: %s\\n\", string(key), string(value), dataType)\n\treturn nil\n}, \"person\", \"name\")\n\n// The most efficient way to extract multiple keys is `EachKey`\n\npaths := [][]string{\n  []string{\"person\", \"name\", \"fullName\"},\n  []string{\"person\", \"avatars\", \"[0]\", \"url\"},\n  []string{\"company\", \"url\"},\n}\njsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, err error){\n  switch idx {\n  case 0: // []string{\"person\", \"name\", \"fullName\"}\n    ...\n  case 1: // []string{\"person\", \"avatars\", \"[0]\", \"url\"}\n    ...\n  case 2: // []string{\"company\", \"url\"},\n    ...\n  }\n}, paths...)\n\n// For more information see docs below\n```\n\n## Reference\n\nLibrary API is really simple. You just need the `Get` method to perform any operation. The rest is just helpers around it.\n\nYou also can view API at [godoc.org](https://godoc.org/github.com/buger/jsonparser)\n\n\n### **`Get`**\n```go\nfunc Get(data []byte, keys ...string) (value []byte, dataType jsonparser.ValueType, offset int, err error)\n```\nReceives data structure, and key path to extract value from.\n\nReturns:\n* `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error\n* `dataType` - \tCan be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null`\n* `offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper.\n* `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`\n\nAccepts multiple keys to specify path to JSON value (in case of quering nested structures).\nIf 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.\n\nNote that keys can be an array indexes: `jsonparser.GetInt(\"person\", \"avatars\", \"[0]\", \"url\")`, pretty cool, yeah?\n\n### **`GetString`**\n```go\nfunc GetString(data []byte, keys ...string) (val string, err error)\n```\nReturns strings properly handing escaped and unicode characters. Note that this will cause additional memory allocations.\n\n### **`GetUnsafeString`**\nIf 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:\n```go\ns, _, := jsonparser.GetUnsafeString(data, \"person\", \"name\", \"title\")\nswitch s {\n  case 'CEO':\n    ...\n  case 'Engineer'\n    ...\n  ...\n}\n```\nNote 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.\n\n\n### **`GetBoolean`**, **`GetInt`** and **`GetFloat`**\n```go\nfunc GetBoolean(data []byte, keys ...string) (val bool, err error)\n\nfunc GetFloat(data []byte, keys ...string) (val float64, err error)\n\nfunc GetInt(data []byte, keys ...string) (val int64, err error)\n```\nIf you know the key type, you can use the helpers above.\nIf key data type do not match, it will return error.\n\n### **`ArrayEach`**\n```go\nfunc ArrayEach(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string)\n```\nNeeded for iterating arrays, accepts a callback function with the same return arguments as `Get`.\n\n### **`ObjectEach`**\n```go\nfunc ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)\n```\nNeeded for iterating object, accepts a callback function. Example:\n```go\nvar handler func([]byte, []byte, jsonparser.ValueType, int) error\nhandler = func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error {\n\t//do stuff here\n}\njsonparser.ObjectEach(myJson, handler)\n```\n\n\n### **`EachKey`**\n```go\nfunc EachKey(data []byte, cb func(idx int, value []byte, dataType jsonparser.ValueType, err error), paths ...[]string)\n```\nWhen 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!\n\n```go\npaths := [][]string{\n\t[]string{\"uuid\"},\n\t[]string{\"tz\"},\n\t[]string{\"ua\"},\n\t[]string{\"st\"},\n}\nvar data SmallPayload\n\njsonparser.EachKey(smallFixture, func(idx int, value []byte, vt jsonparser.ValueType, err error){\n\tswitch idx {\n\tcase 0:\n\t\tdata.Uuid, _ = value\n\tcase 1:\n\t\tv, _ := jsonparser.ParseInt(value)\n\t\tdata.Tz = int(v)\n\tcase 2:\n\t\tdata.Ua, _ = value\n\tcase 3:\n\t\tv, _ := jsonparser.ParseInt(value)\n\t\tdata.St = int(v)\n\t}\n}, paths...)\n```\n\n### **`Set`**\n```go\nfunc Set(data []byte, setValue []byte, keys ...string) (value []byte, err error)\n```\nReceives existing data structure, key path to set, and value to set at that key. *This functionality is experimental.*\n\nReturns:\n* `value` - Pointer to original data structure with updated or added key value.\n* `err` - If any parsing issue, it should return error.\n\nAccepts multiple keys to specify path to JSON value (in case of updating or creating  nested structures).\n\nNote that keys can be an array indexes: `jsonparser.Set(data, []byte(\"http://github.com\"), \"person\", \"avatars\", \"[0]\", \"url\")`\n\n### **`Delete`**\n```go\nfunc Delete(data []byte, keys ...string) value []byte\n```\nReceives existing data structure, and key path to delete. *This functionality is experimental.*\n\nReturns:\n* `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.\n\nAccepts multiple keys to specify path to JSON value (in case of updating or creating  nested structures).\n\nNote that keys can be an array indexes: `jsonparser.Delete(data, \"person\", \"avatars\", \"[0]\", \"url\")`\n\n\n## What makes it so fast?\n* It does not rely on `encoding/json`, `reflection` or `interface{}`, the only real package dependency is `bytes`.\n* Operates with JSON payload on byte level, providing you pointers to the original data structure: no memory allocation.\n* 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).\n* Does not parse full record, only keys you specified\n\n\n## Benchmarks\n\nThere are 3 benchmark types, trying to simulate real-life usage for small, medium and large JSON payloads.\nFor each metric, the lower value is better. Time/op is in nanoseconds. Values better than standard encoding/json marked as bold text.\nBenchmarks run on standard Linode 1024 box.\n\nCompared libraries:\n* https://golang.org/pkg/encoding/json\n* https://github.com/Jeffail/gabs\n* https://github.com/a8m/djson\n* https://github.com/bitly/go-simplejson\n* https://github.com/antonholmquist/jason\n* https://github.com/mreiferson/go-ujson\n* https://github.com/ugorji/go/codec\n* https://github.com/pquerna/ffjson\n* https://github.com/mailru/easyjson\n* https://github.com/buger/jsonparser\n\n#### TLDR\nIf you want to skip next sections we have 2 winner: `jsonparser` and `easyjson`.\n`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.\n`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).\n\nIt'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.\n\nIf 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`.\n\n`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.\n\nWith great power comes great responsibility! :)\n\n\n#### Small payload\n\nEach test processes 190 bytes of http log as a JSON record.\nIt should read multiple fields.\nhttps://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payload_test.go\n\nLibrary | time/op | bytes/op | allocs/op \n ------ | ------- | -------- | -------\nencoding/json struct | 7879 | 880 | 18 \nencoding/json interface{} | 8946 | 1521 | 38\nJeffail/gabs | 10053 | 1649 | 46\nbitly/go-simplejson | 10128 | 2241 | 36 \nantonholmquist/jason | 27152 | 7237 | 101 \ngithub.com/ugorji/go/codec | 8806 | 2176 | 31 \nmreiferson/go-ujson | **7008** | **1409** | 37 \na8m/djson | 3862 | 1249 | 30 \npquerna/ffjson | **3769** | **624** | **15** \nmailru/easyjson | **2002** | **192** | **9** \nbuger/jsonparser | **1367** | **0** | **0** \nbuger/jsonparser (EachKey API) | **809** | **0** | **0** \n\nWinners 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.\nIf 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.\n\n#### Medium payload\n\nEach test processes a 2.4kb JSON record (based on Clearbit API).\nIt should read multiple nested fields and 1 array.\n\nhttps://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_payload_test.go\n\n| Library | time/op | bytes/op | allocs/op |\n| ------- | ------- | -------- | --------- |\n| encoding/json struct | 57749 | 1336 | 29 |\n| encoding/json interface{} | 79297 | 10627 | 215 |\n| Jeffail/gabs | 83807 | 11202 | 235 |\n| bitly/go-simplejson | 88187 | 17187 | 220 |\n| antonholmquist/jason | 94099 | 19013 | 247 |\n| github.com/ugorji/go/codec | 114719 | 6712 | 152 |\n| mreiferson/go-ujson | **56972** | 11547 | 270 |\n| a8m/djson | 28525 | 10196 | 198 | \n| pquerna/ffjson | **20298** | **856** | **20** |\n| mailru/easyjson | **10512** | **336** | **12** |\n| buger/jsonparser | **15955** | **0** | **0** |\n| buger/jsonparser (EachKey API) | **8916** | **0** | **0** |\n\nThe 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.\n\n`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.\n`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.\n\n\n#### Large payload\n\nEach test processes a 24kb JSON record (based on Discourse API)\nIt should read 2 arrays, and for each item in array get a few fields.\nBasically it means processing a full JSON file.\n\nhttps://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payload_test.go\n\n| Library | time/op | bytes/op | allocs/op |\n| --- | --- | --- | --- |\n| encoding/json struct | 748336 | 8272 | 307 |\n| encoding/json interface{} | 1224271 | 215425 | 3395 |\n| a8m/djson | 510082 | 213682 | 2845 |\n| pquerna/ffjson | **312271** | **7792** | **298** |\n| mailru/easyjson | **154186** | **6992** | **288** |\n| buger/jsonparser | **85308** | **0** | **0** |\n\n`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)\n\nAlso 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. \n\n## Questions and support\n\nAll bug-reports and suggestions should go though Github Issues.\n\n## Contributing\n\n1. Fork it\n2. Create your feature branch (git checkout -b my-new-feature)\n3. Commit your changes (git commit -am 'Added some feature')\n4. Push to the branch (git push origin my-new-feature)\n5. Create new Pull Request\n\n## Development\n\nAll my development happens using Docker, and repo include some Make tasks to simplify development.\n\n* `make build` - builds docker image, usually can be called only once\n* `make test` - run tests\n* `make fmt` - run go fmt\n* `make bench` - run benchmarks (if you need to run only single benchmark modify `BENCHMARK` variable in make file)\n* `make profile` - runs benchmark and generate 3 files-  `cpu.out`, `mem.mprof` and `benchmark.test` binary, which can be used for `go tool pprof`\n* `make bash` - enter container (i use it for running `go tool pprof` above)\n","funding_links":[],"categories":["开源类库","Misc","Go","Repositories","Open source library","Libraries"],"sub_categories":["JSON"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbuger%2Fjsonparser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbuger%2Fjsonparser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbuger%2Fjsonparser/lists"}