### Basic GJSON Get Examples Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/get-functions.md Demonstrates basic usage of the GJSON Get function for simple and nested paths, array access, and retrieving array counts. Ensure the JSON structure matches the path. ```go json := `{ "name": "John", "age": 30, "items": [1, 2, 3], "active": true }` // Simple path name := gjson.Get(json, "name") // "John" // Nested path // If nested object existed: gjson.Get(json, "user.profile.name") // Array access first := gjson.Get(json, "items.0") // 1 count := gjson.Get(json, "items.#") // 3 // Wildcards // all := gjson.Get(json, "items.*") // Modifiers // upper := gjson.Get(json, "name|@upper") // "JOHN" ``` -------------------------------- ### Install GJSON Source: https://github.com/tidwall/gjson/blob/master/README.md Install the GJSON library using the Go tool. Ensure Go is installed on your system. ```sh go get -u github.com/tidwall/gjson ``` -------------------------------- ### Type.String() Method Example Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Demonstrates how to get the string representation of a Type constant. This is useful for debugging or logging. ```go result := gjson.Get(json, "age") if result.Type == gjson.Number { fmt.Println(result.Type.String()) // Output: "Number" } ``` -------------------------------- ### Example: DisableModifiers Usage Source: https://github.com/tidwall/gjson/blob/master/_autodocs/configuration.md Demonstrates enabling and disabling modifier processing. When DisableModifiers is true, paths starting with '@' are treated as literal keys and the pipe character '|' has no special meaning. ```go // Default: modifiers are enabled json := `{"items":[1,2,3]}` result := gjson.Get(json, "items|@reverse") // Result: [3,2,1] // Disable modifiers for untrusted input gjson.DisableModifiers = true result = gjson.Get(untrustedJSON, untrustedPath) // Modifiers in path are ignored gjson.DisableModifiers = false // Re-enable for trusted code result = gjson.Get(json, "items|@reverse") // Result: [3,2,1] ``` -------------------------------- ### Get Function Signature Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/get-functions.md The Get function signature in Go. It takes a JSON string and a path string, returning a Result. ```go func Get(json, path string) Result ``` -------------------------------- ### Basic Path Syntax Examples Source: https://github.com/tidwall/gjson/blob/master/README.md Demonstrates various path syntaxes for accessing JSON data, including nested objects, arrays, wildcards, and escaped characters. ```json { "name": {"first": "Tom", "last": "Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"first": "Dale", "last": "Murphy", "age": 44, "nets": ["ig", "fb", "tw"]}, {"first": "Roger", "last": "Craig", "age": 68, "nets": ["fb", "tw"]}, {"first": "Jane", "last": "Murphy", "age": 47, "nets": ["ig", "tw"]} ] } ``` ```text "name.last" >> "Anderson" "age" >> 37 "children" >> ["Sara","Alex","Jack"] "children.#" >> 3 "children.1" >> "Alex" "child*.2" >> "Jack" "c?ildren.0" >> "Sara" "fav\.movie" >> "Deer Hunter" "friends.#.first" >> ["Dale","Roger","Jane"] "friends.1.last" >> "Craig" ``` -------------------------------- ### Basic GJSON Path Examples Source: https://github.com/tidwall/gjson/blob/master/SYNTAX.md Retrieve values by object name or array index. Use dot notation for nested objects and numeric indices for arrays. ```go name.last "Anderson" name.first "Tom" age 37 children ["Sara","Alex","Jack"] children.0 "Sara" children.1 "Alex" friends.1 {"first": "Roger", "last": "Craig", "age": 68} friends.1.first "Roger" ``` -------------------------------- ### GJSON Initialization and Configuration Source: https://github.com/tidwall/gjson/blob/master/_autodocs/configuration.md This Go snippet shows how to initialize GJSON, including commented-out examples for adding custom modifiers, disabling modifiers for security-sensitive applications, and managing HTML escaping. ```go package main import ( "github.com/tidwall/gjson" ) func init() { // Add custom modifiers if needed // gjson.AddModifier("custom", customFn) // For security-sensitive applications: // gjson.DisableModifiers = true (then enable only for trusted paths) // For HTML context output: // gjson.DisableEscapeHTML = false (keep default) } ``` -------------------------------- ### Get Elements with Specific Property Source: https://github.com/tidwall/gjson/blob/master/_autodocs/path-syntax.md Use `.#(property)` to find the first element that has a specific property. Append `#` to find all elements that have the property. ```go json := `{ "users": [ {"name":"Alice","email":"alice@example.com"}, {"name":"Bob"}, {"name":"Charlie","email":"charlie@example.com"} ] }` // Get all users with email result := gjson.Get(json, "users.#(email)#") ``` -------------------------------- ### Querying JSON with Conditions Source: https://github.com/tidwall/gjson/blob/master/_autodocs/README.md Illustrates how to find the first JSON object in an array that matches a condition and how to retrieve all objects that satisfy a given condition. The example uses boolean conditions. ```go json := `{ "users": [ {"name":"Alice","age":30,"active":true}, {"name":"Bob","age":25,"active":false}, {"name":"Charlie","age":35,"active":true} ] }` // First match admin := gjson.Get(json, "users.#(active==true)") // All matches actives := gjson.Get(json, "users.#(active==true)#") actives.ForEach(func(_, user gjson.Result) bool { fmt.Println(user.Get("name").String()) return true }) ``` -------------------------------- ### GJSON Type Usage Example Source: https://github.com/tidwall/gjson/blob/master/_autodocs/types.md Demonstrates how to use the Type enumeration with a switch statement to handle different JSON value types returned by gjson.Get. ```go result := gjson.Get(json, "age") switch result.Type { case gjson.Null: fmt.Println("Value is null") case gjson.Number: fmt.Println("Age:", result.Int()) case gjson.String: fmt.Println("Age as string:", result.String()) } ``` -------------------------------- ### Working with JSON Arrays Source: https://github.com/tidwall/gjson/blob/master/_autodocs/README.md Shows how to get the length of an array, access individual elements by index, and iterate over all elements in a JSON array. Assumes the JSON contains an array field. ```go json := `{"items":[1,2,3,4,5]}` // Get array length count := gjson.Get(json, "items.#").Int() // 5 // Get element item := gjson.Get(json, "items.0").Int() // 1 // Get all for _, v := range gjson.Get(json, "items").Array() { fmt.Println(v.Int()) } ``` -------------------------------- ### Get a Value from JSON String Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Retrieve a value from a JSON string using a path. ```go json := `{"name":"John","age":30}` result := gjson.Get(json, "name") fmt.Println(result.String()) // "John" ``` -------------------------------- ### GJSON Path Array Length and Elements Source: https://github.com/tidwall/gjson/blob/master/SYNTAX.md Use '#' to get the length of an array or to retrieve all elements within an array. ```go friends.# 3 friends.#.age [44,68,47] ``` -------------------------------- ### Get All Matches with Condition Source: https://github.com/tidwall/gjson/blob/master/_autodocs/path-syntax.md Append `#` to the query to retrieve all elements that match a condition, instead of just the first. This is useful for collecting multiple results. ```go json := `{ "users": [ {"name":"Alice","age":35}, {"name":"Bob","age":22}, {"name":"Charlie","age":38} ] }` // Get all users over 30 result := gjson.Get(json, "users.#(age>30)#") // Returns array of all matching results // Get names of all users over 30 names := gjson.Get(json, "users.#(age>30)#.name") ``` -------------------------------- ### GJSON Get and Error Handling Pattern Source: https://github.com/tidwall/gjson/blob/master/_autodocs/README.md Demonstrates the recommended pattern for using gjson.Get, including checking for existence and performing type checks before operations. This pattern ensures safe access and conversion of JSON data. ```go result := gjson.Get(json, "path.to.value") // Always check if !result.Exists() { return fmt.Errorf("path not found") } // Type check before operations if !result.IsArray() { return fmt.Errorf("expected array, got %s", result.Type.String()) } // Safe conversion value := result.String() // Works for any type ``` -------------------------------- ### Get JSON from Bytes Source: https://github.com/tidwall/gjson/blob/master/README.md Demonstrates using `GetBytes` to efficiently parse JSON directly from a `[]byte` slice. This is preferred over converting the byte slice to a string. ```go var json []byte = ... result := gjson.GetBytes(json, path) ``` -------------------------------- ### Find JSON Matches by Name Pattern Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Use pattern matching with '%' to find JSON objects where a field, like 'name', starts with a specific string. ```go // Names starting with J result := gjson.Get(json, `users.#(name%"J*")#.name`) ``` -------------------------------- ### Get Value at Path Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Searches within a JSON Result for a specified dot-notation path. Returns a new Result adjusted to the original JSON. ```Go user := gjson.Get(json, "user") name := user.Get("profile.name") ``` -------------------------------- ### Get Integer with Default Value Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Safely retrieve an integer value from JSON, returning a default if the path does not exist. Useful for configuration settings. ```go func getIntWithDefault(result gjson.Result, path string, def int64) int64 { val := result.Get(path) if !val.Exists() { return def } return val.Int() } ``` -------------------------------- ### Get Multiple Values from JSON Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Retrieve multiple values from a JSON string using a list of paths. ```go results := gjson.GetMany(json, "name", "age", "city") ``` -------------------------------- ### Parse and Get JSON Values Source: https://github.com/tidwall/gjson/blob/master/README.md Demonstrates multiple ways to parse JSON and retrieve nested values using GJSON. Use these methods for simple and direct access to JSON data. ```go gjson.Parse(json).Get("name").Get("last") gjson.Get(json, "name").Get("last") gjson.Get(json, "name.last") ``` -------------------------------- ### Get Function Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/get-functions.md Searches JSON for the specified path and returns a Result. Supports dot notation, wildcards, arrays, queries, and modifiers. ```APIDOC ## Get Searches JSON for the specified path and returns a Result. Supports dot notation, wildcards, arrays, queries, and modifiers. ### Signature ```go func Get(json, path string) Result ``` ### Parameters #### Path Parameters - **json** (string) - Required - JSON string to search - **path** (string) - Required - Path in dot notation (e.g., "user.profile.name") ### Returns - **Result** - The value at the specified path, or empty Result if not found. ### Path Syntax - Dot notation: `"name.first"` accesses nested objects - Array indexing: `"items.0"` accesses array element by index - Array length: `"items.#"` returns count of items - Wildcards: `"items.*"` matches all items, `"items.?"` matches single character - Queries: `"items.#(active==true)"` finds first match, `"items.#(active==true)#"` finds all - Modifiers: `"name|@lower"` applies modifier functions - Escaping: `"field\.with\.dots"` escapes special characters - JSON Lines: `"..#"` treats input as JSON lines array ### Example ```go json := `{ "name": "John", "age": 30, "items": [1, 2, 3], "active": true }` // Simple path name := gjson.Get(json, "name") // "John" // Nested path // If nested object existed: gjson.Get(json, "user.profile.name") // Array access first := gjson.Get(json, "items.0") // 1 count := gjson.Get(json, "items.#") // 3 // Wildcards // all := gjson.Get(json, "items.*") // Modifiers // upper := gjson.Get(json, "name|@upper") // "JOHN" ``` ### Available Modifiers - `@reverse` - reverse array or object members - `@ugly` - remove whitespace - `@pretty` - format with indentation - `@this` - return current element - `@valid` - validate JSON - `@flatten` - flatten arrays - `@join` - join objects - `@keys` - array of object keys - `@values` - array of object values - `@tostr` - convert to string - `@fromstr` - convert from string - `@group` - group arrays of objects - `@dig` - recursive search ``` -------------------------------- ### GJSON Multipath Example Source: https://github.com/tidwall/gjson/blob/master/SYNTAX.md Selects specific fields and nested values from a JSON document to form a new JSON object. An optional key 'the_murphys' is provided to assign a specific key to a value. ```go {name.first,age,"the_murphys":friends.#(last="Murphy")#.first} ``` -------------------------------- ### GetBytes Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/get-functions.md Searches JSON bytes for the specified path. This is the preferred method over Get(string(data), path) for performance reasons when dealing with byte slices. ```APIDOC ## GetBytes ### Description Searches JSON bytes for the specified path. Preferred over Get(string(data), path). ### Method func GetBytes(json []byte, path string) Result ### Parameters #### Path Parameters - **json** ([]byte) - Required - JSON bytes to search - **path** (string) - Required - Path in dot notation ### Response #### Success Response - **Result** - The value at the specified path. ### Request Example ```go data := []byte(`{"name":"John","age":30}`) name := gjson.GetBytes(data, "name") fmt.Println(name.String()) // "John" // Getting raw bytes from original age := gjson.GetBytes(data, "age") if age.Index > 0 { rawAge := data[age.Index : age.Index+len(age.Raw)] fmt.Println(string(rawAge)) // "30" } ``` ``` -------------------------------- ### GJSON Result Usage Example Source: https://github.com/tidwall/gjson/blob/master/_autodocs/types.md Shows how to use the Result struct to access and manipulate parsed JSON data, including type checking and retrieving values like strings, integers, and arrays. ```go json := `{ "user": { "name": "John", "age": 30, "tags": ["dev", "go", "json"] } }` result := gjson.Get(json, "user") // Check type if result.IsObject() { // Access as object name := result.Get("name") fmt.Println(name.String()) // "John" age := result.Get("age") fmt.Println(age.Int()) // 30 tags := result.Get("tags") if tags.IsArray() { for _, tag := range tags.Array() { fmt.Println(tag.String()) } } } ``` -------------------------------- ### Get Operations Source: https://github.com/tidwall/gjson/blob/master/_autodocs/README.md These functions allow you to query JSON data using a specified path. They are designed for fast parsing without full unmarshaling. ```APIDOC ## Get(json, path) ### Description Queries a JSON string by the given path. ### Parameters - **json** (string) - The JSON string to query. - **path** (string) - The path to the desired value. ### Returns - **Result** (gjson.Result) - The result of the query. ``` ```APIDOC ## GetBytes(data, path) ### Description Queries a JSON byte slice by the given path. ### Parameters - **data** ([]byte) - The JSON byte slice to query. - **path** (string) - The path to the desired value. ### Returns - **Result** (gjson.Result) - The result of the query. ``` ```APIDOC ## GetMany(json, paths...) ### Description Queries a JSON string for multiple paths simultaneously. ### Parameters - **json** (string) - The JSON string to query. - **paths** (string...) - A variadic list of paths to query. ### Returns - **Results** ([]gjson.Result) - A slice of results corresponding to the queried paths. ``` ```APIDOC ## Parse(json) ### Description Parses a JSON string and returns a `Result` object that allows for chaining queries. ### Parameters - **json** (string) - The JSON string to parse. ### Returns - **Result** (gjson.Result) - The parsed JSON result object. ``` -------------------------------- ### Get String with Default Value Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Safely retrieve a string value from JSON, returning a default if the path does not exist. Ideal for optional string fields. ```go func getStringWithDefault(result gjson.Result, path, def string) string { val := result.Get(path) if !val.Exists() { return def } return val.String() } ``` -------------------------------- ### Get First Match with Condition Source: https://github.com/tidwall/gjson/blob/master/_autodocs/path-syntax.md Use `.#(condition)` to find the first element matching a specific condition. Supported operators include `==`, `!=`, `<`, `<=`, `>`, `>=`, `%` (pattern match), and `!%` (not pattern match). ```go json := `{ "users": [ {"name":"Alice","active":true}, {"name":"Bob","active":false}, {"name":"Charlie","active":true} ] }` // Get first active user result := gjson.Get(json, "users.#(active==true)") fmt.Println(result.Get("name").String()) // "Alice" // Get first user over 25 result := gjson.Get(json, "users.#(age>25)") ``` -------------------------------- ### Efficiently Get Raw Bytes from JSON Bytes Source: https://github.com/tidwall/gjson/blob/master/README.md Illustrates a pattern for obtaining a sub-slice of the original JSON byte array corresponding to a result's raw data, minimizing allocations. It utilizes `result.Index` for direct slicing when possible. ```go var json []byte = ... result := gjson.GetBytes(json, path) var raw []byte if result.Index > 0 { raw = json[result.Index:result.Index+len(result.Raw)] } else { raw = []byte(result.Raw) } ``` -------------------------------- ### Get a JSON Value Source: https://github.com/tidwall/gjson/blob/master/README.md Retrieve a specific value from a JSON string using a dot-notation path. The `String()` method is used to get the value as a string. ```go package main import "github.com/tidwall/gjson" const json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}` func main() { value := gjson.Get(json, "name.last") println(value.String()) } ``` -------------------------------- ### Get Paths for Multi-Result Elements Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Retrieve the GJSON paths for all elements within a multi-result, typically obtained using '#' queries. This method requires the original JSON string. It does not work with multipaths, modifiers, or nested queries. ```go result := gjson.Get(json, "users.#(age>30)") paths := result.Paths(json) for _, path := range paths { fmt.Println(path) // e.g., "users.0", "users.2" } ``` -------------------------------- ### Get Float Value from JSON Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use the Float() method to get a float64 representation of a JSON value. This is useful for numerical fields that should be treated as floating-point numbers. ```Go result := gjson.Get(`{"price":19.99}`, "price") price := result.Float() fmt.Printf("Price: $%.2f\n", price) ``` -------------------------------- ### Usage of Default Value Functions Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Demonstrates how to use the `getIntWithDefault` and `getStringWithDefault` functions to provide fallback values for JSON properties. ```go // Usage data := gjson.Parse(json) timeout := getIntWithDefault(data, "config.timeout", 30) host := getStringWithDefault(data, "config.host", "localhost") ``` -------------------------------- ### Get Int64 Representation of Result Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use Result.Int() to get a 64-bit signed integer representation of the Result value. Supports the full 64-bit integer range. ```Go result := gjson.Get(`{"count":42}`, "count") count := result.Int() fmt.Printf("Count: %d\n", count) ``` -------------------------------- ### Basic JSON Query Source: https://github.com/tidwall/gjson/blob/master/_autodocs/README.md Demonstrates how to retrieve a string value from a JSON object using a simple path. Ensure the 'github.com/tidwall/gjson' package is imported. ```go import "github.com/tidwall/gjson" json := `{"user":{"name":"John","age":30}}` result := gjson.Get(json, "user.name") fmt.Println(result.String()) // "John" ``` -------------------------------- ### Get Uint64 Representation of Result Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use Result.Uint() to get a 64-bit unsigned integer representation of the Result value. Supports the full 64-bit unsigned integer range. ```Go result := gjson.Get(`{"id":12345}`, "id") id := result.Uint() fmt.Printf("ID: %d\n", id) ``` -------------------------------- ### Get String Representation of Result Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use Result.String() to get a string representation of the Result value. It handles numbers, strings, JSON, booleans, and null values appropriately. ```Go result := gjson.Get(`{"name":"John"}`, "name") println(result.String()) // Output: John ``` -------------------------------- ### Pretty Print with Options Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Apply the `@pretty` modifier with custom options, such as sorting keys and specifying indentation. ```go result := gjson.Get(json, `data|@pretty:{"sortKeys":true,"indent":" "}`) ``` -------------------------------- ### Read Configuration File Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Load configuration settings from a file using gjson. Parses byte data to extract string, integer, and boolean values. ```go func loadConfig(path string) (Config, error) { data, _ := ioutil.ReadFile(path) cfg := Config{ Host: gjson.GetBytes(data, "host").String(), Port: int(gjson.GetBytes(data, "port").Int()), Debug: gjson.GetBytes(data, "debug").Bool(), Timeout: int(gjson.GetBytes(data, "timeout").Int()), } return cfg, nil } ``` -------------------------------- ### Import gjson Package Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Import the gjson package to use its functionalities. ```go import "github.com/tidwall/gjson" ``` -------------------------------- ### Result.IsArray() Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Checks if the Result represents a JSON array. This is true if the JSON value starts with '['. ```APIDOC ## Result.IsArray() ### Description Checks if the Result represents a JSON array. This is true if the JSON value starts with '['. ### Method func (t Result) IsArray() bool ### Returns `bool` — True if the Result is a JSON array (starts with '['). ### Example ```go result := gjson.Get(json, "tags") if result.IsArray() { for _, tag := range result.Array() { fmt.Println(tag.String()) } } ``` ``` -------------------------------- ### Result.IsObject() Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Checks if the Result represents a JSON object. This is true if the JSON value starts with '{'. ```APIDOC ## Result.IsObject() ### Description Checks if the Result represents a JSON object. This is true if the JSON value starts with '{'. ### Method func (t Result) IsObject() bool ### Returns `bool` — True if the Result is a JSON object (starts with '{'). ### Example ```go result := gjson.Get(json, "user") if result.IsObject() { fmt.Println("User is an object") } ``` ``` -------------------------------- ### Advanced Path Syntax with Queries Source: https://github.com/tidwall/gjson/blob/master/README.md Illustrates advanced path queries using comparison operators and pattern matching within array elements. Note the syntax change from `#[...]` to `#(...)` in v1.3.0. ```text friends.#(last=="Murphy").first >> "Dale" friends.#(last=="Murphy")#.first >> ["Dale","Jane"] friends.#(age>45)#.last >> ["Craig","Murphy"] friends.#(first%"D*").last >> "Murphy" friends.#(first!%"D*").last >> "Craig" friends.#(nets.#(=="fb"))#.first >> ["Dale","Roger"] ``` -------------------------------- ### Get a Value from JSON Bytes Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Retrieve a value from a JSON byte slice using a path. ```go data := []byte(`{"name":"John"}`) result := gjson.GetBytes(data, "name") ``` -------------------------------- ### Get Object Values with @values Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/modifiers.md The @values modifier returns an array containing all the values of a JSON object. ```go json := `{"x":10,"y":20,"z":30}` result := gjson.Get(json, ".|@values") // Result: [10,20,30] ``` -------------------------------- ### Get Object Keys with @keys Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/modifiers.md The @keys modifier returns an array containing all the keys of a JSON object. ```go json := `{"name":"John","age":30,"city":"NYC"}` result := gjson.Get(json, ".|@keys") // Result: ["name","age","city"] ``` -------------------------------- ### AddModifier Source: https://github.com/tidwall/gjson/blob/master/_autodocs/configuration.md Registers a custom modifier function that can be used in Get() paths. This function should be called during initialization as it is not thread-safe. ```APIDOC ## AddModifier ### Description Registers a custom modifier function. ### Signature ```go func AddModifier(name string, fn func(json, arg string) string) ``` ### Parameters #### Path Parameters - **name** (string) - Required - Modifier name (without @) - **fn** (func(json, arg string) string) - Required - Function taking JSON and optional argument ### Thread Safety Not thread-safe. Call during initialization, not concurrently. ### Timing Must be called before using the modifier in Get() paths. ### Example ```go // Register custom modifier at startup func init() { // Simple modifier without argument gjson.AddModifier("upper", func(json, arg string) string { return strings.ToUpper(json) }) // Modifier with argument gjson.AddModifier("repeat", func(json, arg string) string { count := 1 if n, err := strconv.Atoi(arg); err == nil { count = n } result := "" for i := 0; i < count; i++ { result += json } return result }) // Modifier using parsed JSON gjson.AddModifier("double", func(json, arg string) string { res := gjson.Parse(json) if res.Type == gjson.Number { num := res.Num * 2 return strconv.FormatFloat(num, 'f', -1, 64) } return json }) } // Use in paths result := gjson.Get(json, "name|@upper") result = gjson.Get(json, "text|@repeat:3") result = gjson.Get(json, "amount|@double") ``` ``` -------------------------------- ### Dot vs Pipe Separators in GJSON Paths Source: https://github.com/tidwall/gjson/blob/master/SYNTAX.md Demonstrates the equivalence and differences between dot (.) and pipe (|) separators in GJSON paths, especially when used with array indices and the '#' operator. ```go friends.0.first "Dale" friends|0.first "Dale" friends.0|first "Dale" friends|0|first "Dale" friends|# 3 friends.# 3 friends.#(last="Murphy")# [{"first": "Dale", "last": "Murphy", "age": 44},{"first": "Jane", "last": "Murphy", "age": 47}] friends.#(last="Murphy")#.first ["Dale","Jane"] friends.#(last="Murphy")#|first friends.#(last="Murphy")#.0 [] friends.#(last="Murphy")#|0 {"first": "Dale", "last": "Murphy", "age": 44} friends.#(last="Murphy")#.# [] friends.#(last="Murphy")#|# 2 ``` -------------------------------- ### Get Nested Array Values Source: https://github.com/tidwall/gjson/blob/master/README.md Query nested array elements using the '#' wildcard and filter by object properties. ```json { "programmers": [ { "firstName": "Janet", "lastName": "McLaughlin", }, { "firstName": "Elliotte", "lastName": "Hunter", }, { "firstName": "Jason", "lastName": "Harold", } ] } ``` ```go result := gjson.Get(json, "programmers.#.lastName") for _, name := range result.Array() { println(name.String()) } ``` ```go name := gjson.Get(json, `programmers.#(lastName="Hunter").firstName`) println(name.String()) // prints "Elliotte" ``` -------------------------------- ### Result Type Definition Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Defines the structure of a Result, which holds parsed JSON values and metadata from Get operations. ```go type Result struct { Type Type // The JSON type (Null, False, Number, String, True, or JSON) Raw string // The raw JSON string Str string // The parsed string value (for String types) Num float64 // The parsed numeric value (for Number types) Index int // Position of raw value in original JSON, zero means unknown Indexes []int // Positions of elements matching a '#' query path } ``` -------------------------------- ### Wildcard Matching for Properties and Array Elements Source: https://github.com/tidwall/gjson/blob/master/_autodocs/path-syntax.md Use the '*' wildcard to match all properties of an object or all elements of an array. This is powerful for retrieving multiple values that match a pattern. ```go json := `{ "users": { "alice": {"age": 30}, "bob": {"age": 25}, "charlie": {"age": 35} } }` // Get all ages result := gjson.Get(json, "users.*.age") // Returns [30, 25, 35] ``` -------------------------------- ### Path Syntax Source: https://github.com/tidwall/gjson/blob/master/_autodocs/MANIFEST.txt Reference for GJSON's powerful path syntax, including operators, wildcards, and modifiers. ```APIDOC ## Path Syntax ### Description Details the syntax used for querying JSON data with GJSON. ### Features - **Dot notation**: Access object fields (e.g., `user.name`). - **Array indexing**: Access array elements by index (e.g., `users.0.name`). - **Wildcards**: Match all elements in an array or object (e.g., `users.*.name`). - **Query operators**: Filter arrays based on conditions (e.g., `users.?»name == 'John'*`). Supported operators: `==`, `!=`, `<`, `>`, `<=`, `>=`, `%` (contains), `!%` (does not contain). - **Pattern matching**: Use wildcards within query operators (e.g., `users.?»name like 'J*'*`). - **Nested queries**: Combine multiple path segments and operators. - **Modifiers**: Apply transformations to results (e.g., `users.@keys`). - **Chaining**: Apply multiple modifiers sequentially. - **Escaping**: Handle special characters in keys or values using backslashes. - **JSON Lines**: Support for parsing newline-delimited JSON. ``` -------------------------------- ### Get Array Length Source: https://github.com/tidwall/gjson/blob/master/_autodocs/path-syntax.md Retrieve the number of elements in a JSON array using the '#' suffix. This is useful for determining the size of collections. ```go json := `{"items":[1,2,3,4,5]}` result := gjson.Get(json, "items.#") fmt.Println(result.Int()) // 5 ``` -------------------------------- ### Configuration Options Source: https://github.com/tidwall/gjson/blob/master/_autodocs/README.md Global configuration settings that affect the behavior of GJSON functions. ```APIDOC ## Configuration ### `DisableModifiers` #### Description When set to true, modifier processing is disabled globally. ### `DisableEscapeHTML` #### Description When set to true, HTML character escaping is disabled globally. ### `AddModifier(name, fn)` #### Description Registers a custom modifier function with the given name. ### `ModifierExists(name, fn)` #### Description Checks if a modifier with the given name already exists. ``` -------------------------------- ### Get Current Element with @this Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/modifiers.md The @this modifier returns the current element being processed, useful for accessing the root or intermediate results in a path. ```go json := `{"data":{"nested":true}}` result := gjson.Get(json, "data|@this") // Result: {"nested":true} ``` -------------------------------- ### Parse JSON and Then Query Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Parse a JSON string first and then query nested values. ```go result := gjson.Parse(json).Get("user").Get("name") ``` -------------------------------- ### Check if Result is a JSON Object Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use IsObject() to determine if the Result represents a JSON object. This is true if the JSON starts with '{'. ```go result := gjson.Get(json, "user") if result.IsObject() { fmt.Println("User is an object") } ``` -------------------------------- ### Configuration Source: https://github.com/tidwall/gjson/blob/master/_autodocs/MANIFEST.txt Options for configuring GJSON behavior, such as modifier management and HTML escaping. ```APIDOC ## Configuration ### Description Global configuration options that affect GJSON's behavior. ### Options - **DisableModifiers**: A boolean flag to disable all modifiers. - **DisableEscapeHTML**: A boolean flag to disable HTML escaping in string results. - **Modifier management**: Functions to add, remove, and check for custom modifiers. ``` -------------------------------- ### Pretty Print JSON with Sorted Keys Source: https://github.com/tidwall/gjson/blob/master/README.md Shows how to use the @pretty modifier with arguments to format JSON output, including sorting keys. ```json @pretty:{"sortKeys":true} ``` -------------------------------- ### Handle Nonexistent Path Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Check if a path exists in the JSON. Use `Exists()` to safely handle cases where a path might not be present. ```go result := gjson.Get(json, "nonexistent.path") if !result.Exists() { fmt.Println("Path not found") } ``` -------------------------------- ### Dynamic Path Construction Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Dynamically construct a JSON path by iterating through a slice of keys and escaping each one. This allows for flexible navigation of nested JSON structures. ```Go func getNestedValue(json string, keys ...string) gjson.Result { result := gjson.Parse(json) for _, key := range keys { // Escape each key component escaped := gjson.Escape(key) result = result.Get(escaped) if !result.Exists() { break } } return result } // Usage json := `{"a":{"b":{"c":"value"}}}` value := getNestedValue(json, "a", "b", "c") fmt.Println(value.String()) // "value" ``` -------------------------------- ### Using '@pretty' Modifier with Arguments Source: https://github.com/tidwall/gjson/blob/master/SYNTAX.md Demonstrates the use of the '@pretty' modifier with a JSON argument to format output, including sorting keys. ```json { "age":37, "children": ["Sara","Alex","Jack"], "fav.movie": "Deer Hunter", "friends": [ {"age": 44, "first": "Dale", "last": "Murphy"}, {"age": 68, "first": "Roger", "last": "Craig"}, {"age": 47, "first": "Jane", "last": "Murphy"} ], "name": {"first": "Tom", "last": "Anderson"} } ``` -------------------------------- ### Nested Navigation in GJSON Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Demonstrates multiple ways to navigate nested JSON structures using GJSON. Supports direct chained calls, or a single path string for accessing deeply nested values. ```go user := gjson.Get(json, "user") profile := user.Get("profile") name := profile.Get("name") // Or chained name := gjson.Get(json, "user").Get("profile").Get("name") // Or direct name := gjson.Get(json, "user.profile.name") ``` -------------------------------- ### Project Array Elements by Field Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Extract a specific field from all elements in a JSON array. Useful for getting lists of values like names or IDs. ```go json := `{ "users": [ {"id":1,"name":"Alice","age":30}, {"id":2,"name":"Bob","age":25}, {"id":3,"name":"Charlie","age":35} ] }` // Get array of names names := gjson.Get(json, "users.#.name") // Result: ["Alice","Bob","Charlie"] ``` -------------------------------- ### GJSON Performance: Direct Access vs. Targeted Query Source: https://github.com/tidwall/gjson/blob/master/_autodocs/path-syntax.md Direct access to a specific field is faster than using a targeted query. Use direct access when the exact path is known. ```go // Fast: direct access id := gjson.Get(json, "users.0.id") ``` -------------------------------- ### GJSON Path Array Queries Source: https://github.com/tidwall/gjson/blob/master/SYNTAX.md Query arrays for specific elements using '#(...)' for the first match or '#(...)#' for all matches. Supports comparison operators and pattern matching. ```go friends.#(last=="Murphy").first "Dale" friends.#(last=="Murphy")#.first ["Dale","Jane"] friends.#(age>45)#.last ["Craig","Murphy"] friends.#(first%"D*").last "Murphy" friends.#(first!%"D*").last "Craig" ``` ```go children.#(!%"*a*") "Alex" children.#(%"*a*")# ["Sara","Jack"] ``` ```go friends.#(nets.#(=="fb"))#.first >> ["Dale","Roger"] ``` -------------------------------- ### Register Custom Modifiers Source: https://github.com/tidwall/gjson/blob/master/_autodocs/configuration.md Register custom modifier functions to extend GJSON functionality. Call during initialization before using the modifier in Get() paths. Not thread-safe. ```go func init() { // Simple modifier without argument gjson.AddModifier("upper", func(json, arg string) string { return strings.ToUpper(json) }) // Modifier with argument gjson.AddModifier("repeat", func(json, arg string) string { count := 1 if n, err := strconv.Atoi(arg); err == nil { count = n } result := "" for i := 0; i < count; i++ { result += json } return result }) // Modifier using parsed JSON gjson.AddModifier("double", func(json, arg string) string { res := gjson.Parse(json) if res.Type == gjson.Number { num := res.Num * 2 return strconv.FormatFloat(num, 'f', -1, 64) } return json }) } // Use in paths result := gjson.Get(json, "name|@upper") result = gjson.Get(json, "text|@repeat:3") result = gjson.Get(json, "amount|@double") ``` -------------------------------- ### GJSON Path Wildcard Usage Source: https://github.com/tidwall/gjson/blob/master/SYNTAX.md Use '*' to match zero or more characters and '?' to match exactly one character in object keys or array indices. ```go child*.2 "Jack" c?ildren.0 "Sara" ``` -------------------------------- ### Check Modifier Existence Source: https://github.com/tidwall/gjson/blob/master/_autodocs/configuration.md Check if a custom modifier has already been registered before attempting to add it. This prevents re-registration and ensures modifiers are available when used in Get() paths. ```go if !gjson.ModifierExists("uppercase", nil) { gjson.AddModifier("uppercase", func(json, arg string) string { return strings.ToUpper(json) }) } // Use only if exists if gjson.ModifierExists("custom", nil) { result := gjson.Get(json, "field|@custom") } ``` -------------------------------- ### Check if Result is a JSON Array Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use IsArray() to check if the Result represents a JSON array. This is true if the JSON starts with '['. It can be iterated using the Array() method. ```go result := gjson.Get(json, "tags") if result.IsArray() { for _, tag := range result.Array() { fmt.Println(tag.String()) } } ``` -------------------------------- ### Type Checking with GJSON Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Shows how to verify the data type of a value retrieved by GJSON. Use this to ensure data integrity and prevent runtime errors. ```Go result := gjson.Get(json, "user.roles") if !result.IsArray() { return fmt.Errorf("roles should be an array") } ``` -------------------------------- ### Conditional Query with Nested Arrays Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Perform a conditional query on nested arrays to find specific elements. This example finds friends who have a Twitter network entry. ```Go // Find friends who have Twitter result := gjson.Get(json, `friends.#(nets.#(=="tw"))#.first`) ``` -------------------------------- ### GJSON Benchmark Results Source: https://github.com/tidwall/gjson/blob/master/README.md Shows the performance metrics for GJSON and other JSON libraries. Metrics include operations per second, nanoseconds per operation, bytes per operation, and allocations per operation. ```text BenchmarkGJSONGet-10 17893731 202.1 ns/op 0 B/op 0 allocs/op BenchmarkGJSONUnmarshalMap-10 1663548 2157 ns/op 1920 B/op 26 allocs/op BenchmarkJSONUnmarshalMap-10 832236 4279 ns/op 2920 B/op 68 allocs/op BenchmarkJSONUnmarshalStruct-10 1076475 3219 ns/op 920 B/op 12 allocs/op BenchmarkJSONDecoder-10 585729 6126 ns/op 3845 B/op 160 allocs/op BenchmarkFFJSONLexer-10 2508573 1391 ns/op 880 B/op 8 allocs/op BenchmarkEasyJSONLexer-10 3000000 537.9 ns/op 501 B/op 5 allocs/op BenchmarkJSONParserGet-10 13707510 263.9 ns/op 21 B/op 0 allocs/op BenchmarkJSONIterator-10 3000000 561.2 ns/op 693 B/op 14 allocs/op ``` -------------------------------- ### Get Path for Single-Result Value Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Obtain the GJSON path for a single-result value. This method requires the original JSON string. It does not work with multipaths, modifiers, or nested queries. ```go result := gjson.Get(json, "users.#(name==John)") path := result.Path(json) fmt.Println(path) // e.g., "users.1" ``` -------------------------------- ### Get JSON Array as []Result Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use the Array() method to retrieve a JSON array as a slice of Result values. If the JSON value is not an array, it returns a single-element array. ```Go result := gjson.Get(`{"items":[1,2,3]}`, "items") for _, item := range result.Array() { fmt.Println(item.Int()) } ``` -------------------------------- ### Check Field Existence Before Use Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Safely retrieves an optional field from JSON and checks if it exists before processing its string value. Use this pattern to handle potentially missing fields gracefully. ```go result := gjson.Get(json, "optional.field") if result.Exists() { process(result.String()) } ``` -------------------------------- ### Iterate Over Values in GJSON Result Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use Result.Values() to get an iterator that yields only the values from a JSON object or array. This is suitable when you are interested in the data content without the keys or indices. ```go for value := range result.Values() { fmt.Println(value.String()) } ``` -------------------------------- ### Type-Safe JSON Extraction Source: https://github.com/tidwall/gjson/blob/master/_autodocs/README.md Demonstrates how to parse JSON into a GJSON result and safely extract values as specific types (string, int, bool). It also shows how to check for the existence of a key before attempting extraction. ```go data := gjson.Parse(json) // Safe conversions name := data.Get("user.name").String() age := data.Get("user.age").Int() active := data.Get("user.active").Bool() // Check existence if data.Get("user.email").Exists() { email := data.Get("user.email").String() } ``` -------------------------------- ### Process JSON Lines from File Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Read and process a newline-delimited JSON file line by line using bufio.Scanner. ```Go // Read and process JSON lines file file, _ := os.Open("data.jsonl") deffer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { line := scanner.Bytes() // Process single line result := gjson.GetBytes(line, "user.name") fmt.Println(result.String()) } ``` -------------------------------- ### Get Boolean Representation of Result Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use Result.Bool() to retrieve a boolean value. It returns true for 'true' strings or non-zero numbers, and false for 'false', null, or zero numbers. ```Go result := gjson.Get(`{"active":true}`, "active") if result.Bool() { fmt.Println("Active") } ``` -------------------------------- ### Handle Type Mismatch Source: https://github.com/tidwall/gjson/blob/master/_autodocs/quick-reference.md Ensure a JSON path points to the expected type before processing. Use `IsArray()` to verify if the result is an array. ```go result := gjson.Get(json, "items") if !result.IsArray() { fmt.Println("Not an array") return } for _, item := range result.Array() { // Safe to use } ``` -------------------------------- ### GJSON Performance: Broad Query with All Matches Source: https://github.com/tidwall/gjson/blob/master/_autodocs/path-syntax.md Retrieving all matches from a broad query can be slower. This is useful when all matching elements are required, but be mindful of performance implications. ```go // Slower: broad query with all matches all := gjson.Get(json, "users.#(role==admin)#") ``` -------------------------------- ### Iterate Over All Key-Value Pairs in GJSON Result Source: https://github.com/tidwall/gjson/blob/master/_autodocs/api-reference/result-type.md Use Result.All() to get an iterator for (key, value) pairs from a JSON object or array. This is useful for processing each element within a JSON structure. ```go for key, value := range result.All() { fmt.Printf("%s: %v\n", key.String(), value.String()) } ``` -------------------------------- ### Validate Multiple Required Paths with GJSON Source: https://github.com/tidwall/gjson/blob/master/_autodocs/advanced-patterns.md Illustrates how to use GJSON's GetMany to retrieve multiple values and validate that required fields exist. This is efficient for checking several fields at once. ```Go paths := []string{"user.name", "user.email", "user.age"} required := []string{"user.name", "user.email"} results := gjson.GetMany(json, paths...) for i, path := range required { if !results[i].Exists() { return fmt.Errorf("required field missing: %s", path) } } ```