Introduction
GJSON is a Go package that lets you retrieve values from JSON strings using a path syntax, without needing to unmarshal into structs or maps. It is designed for speed and simplicity when you only need to read specific fields from a JSON payload.
What GJSON Does
- Retrieves values from JSON strings using dot-separated paths like
name.first - Supports array indexing, wildcards, and nested queries
- Parses JSON lazily — only scans what is needed to find the target path
- Returns typed results with methods like
.String(),.Int(),.Float(),.Bool() - Works with raw JSON bytes or strings, no allocation-heavy unmarshaling
Architecture Overview
GJSON operates as a single-pass scanner over the raw JSON byte slice. When you call gjson.Get(), it walks the JSON from left to right, matching path components as it encounters keys. Once the target is found, it returns a Result value that wraps the raw JSON segment. This lazy approach avoids parsing the entire document and minimizes allocations.
Self-Hosting & Configuration
- Install with
go get github.com/tidwall/gjson— pure Go, zero dependencies - Import and call
gjson.Get(jsonString, "path")— no setup needed - For multiple lookups, use
gjson.GetMany()to scan once for several paths - Works on
[]byteviagjson.GetBytes()to avoid string conversion overhead - Pair with SJSON (same author) for setting values in JSON
Key Features
- Path syntax supports modifiers like
@reverse,@flatten,@valid - Multipath queries retrieve multiple values in a single scan
- Custom modifiers can be registered for domain-specific transformations
- No reflection or code generation — works with raw strings at runtime
- Consistently outperforms
encoding/jsonunmarshal for partial reads
Comparison with Similar Tools
- encoding/json — full unmarshal into structs; GJSON is faster when you only need a few fields
- jsonparser — similar lazy parsing, but GJSON offers richer path syntax and modifiers
- bytedance/sonic — full JSON codec with JIT; GJSON focuses on read-only path queries
- jq — command-line JSON processor; GJSON is an embeddable Go library
FAQ
Q: Is GJSON safe for concurrent use?
A: Yes, gjson.Get is a pure function with no shared state.
Q: Can GJSON modify JSON?
A: No, GJSON is read-only. Use SJSON (github.com/tidwall/sjson) for mutations.
Q: How does it handle invalid JSON?
A: It returns a zero-value Result. Use gjson.Valid() to check validity first.
Q: Does GJSON support JSON5 or comments? A: No, it only supports standard JSON (RFC 8259).