### Install and Use Example App 'jc' Source: https://github.com/neilotoole/jsoncolor/blob/master/README.md Install the example 'jc' CLI application from the project and pipe JSON data to it for colorized output. ```shell # From project root $ go install ./cmd/jc $ cat ./testdata/sakila_actor.json | jc ``` -------------------------------- ### Install jsoncolor Package Source: https://github.com/neilotoole/jsoncolor/blob/master/README.md Install the jsoncolor package using the go get command. Requires Go 1.17 or later. ```shell go get -u github.com/neilotoole/jsoncolor ``` -------------------------------- ### Helper for fatih/color Integration Source: https://github.com/neilotoole/jsoncolor/blob/master/README.md This example demonstrates using the jsoncolor helper package to integrate with the fatih/color library for more convenient terminal color management. It converts fatih/color configurations to jsoncolor's internal Colors struct. ```go // import "github.com/neilotoole/jsoncolor/helper/fatihcolor" // import "github.com/fatih/color" // import "github.com/mattn/go-colorable" out := colorable.NewColorable(os.Stdout) // needed for Windows enc = json.NewEncoder(out) fclrs := fatihcolor.DefaultColors() // Change some values, just for fun fclrs.Number = color.New(color.FgBlue) fclrs.String = color.New(color.FgCyan) clrs := fatihcolor.ToCoreColors(fclrs) enc.SetColors(clrs) ``` -------------------------------- ### DefaultColors - Getting Default Color Scheme Source: https://context7.com/neilotoole/jsoncolor/llms.txt Provides information on how to retrieve the default color configuration that mimics jq's colorization. ```APIDOC ## DefaultColors Returns a `*Colors` configuration that produces output similar to jq's default colorization scheme. This provides a good starting point for customization. ### Method ```go func DefaultColors() *Colors ``` ### Parameters None ### Request Example ```go package main import ( "fmt" json "github.com/neilotoole/jsoncolor" ) func main() { // Get jq-like default colors clrs := json.DefaultColors() // DefaultColors returns: // - Null: dim (\x1b[2m) // - Bool: bold (\x1b[1m) // - Number: cyan (\x1b[36m) // - String: green (\x1b[32m) // - Key: bold blue (\x1b[34;1m) // - Bytes: dim (\x1b[2m) // - Time: dim green (\x1b[32;2m) // - Punc: no colorization // - TextMarshaler: green (\x1b[32m) fmt.Printf("String color bytes: %v\n", clrs.String) fmt.Printf("Number color bytes: %v\n", clrs.Number) } ``` ### Response #### Success Response (200) Returns a `*Colors` struct containing the default color configurations. #### Response Example ``` String color bytes: [27 91 51 50 109] Number color bytes: [27 91 51 54 109] ``` ``` -------------------------------- ### Create a new JSON encoder with jsoncolor Source: https://context7.com/neilotoole/jsoncolor/llms.txt Initializes an encoder with color support and indentation. Use mattn/go-colorable for proper terminal output on Windows. ```go package main import ( "os" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" ) func main() { // Create encoder with colorable output (needed for Windows compatibility) out := colorable.NewColorable(os.Stdout) enc := json.NewEncoder(out) // Enable colorization with jq-like default colors enc.SetColors(json.DefaultColors()) // Enable pretty-printing with 2-space indent enc.SetIndent("", " ") data := map[string]interface{}{ "name": "Alice", "age": 30, "active": true, "balance": nil, "tags": []string{"admin", "user"}, } if err := enc.Encode(data); err != nil { panic(err) } } ``` -------------------------------- ### Import Segmentio JSON Package Source: https://github.com/neilotoole/jsoncolor/blob/master/SEGMENTIO_README.md Import path for the high-performance segmentio/encoding/json package. ```go import ( "github.com/segmentio/encoding/json" ) ``` -------------------------------- ### Import Standard JSON Package Source: https://github.com/neilotoole/jsoncolor/blob/master/SEGMENTIO_README.md Import path for the standard Go JSON package. ```go import ( "encoding/json" ) ``` -------------------------------- ### Retrieve default color configuration Source: https://context7.com/neilotoole/jsoncolor/llms.txt Accesses the predefined color scheme that mimics the jq command-line tool. Useful as a base for further modifications. ```go package main import ( "fmt" json "github.com/neilotoole/jsoncolor" ) func main() { // Get jq-like default colors clrs := json.DefaultColors() // DefaultColors returns: // - Null: dim (\x1b[2m) // - Bool: bold (\x1b[1m) // - Number: cyan (\x1b[36m) // - String: green (\x1b[32m) // - Key: bold blue (\x1b[34;1m) // - Bytes: dim (\x1b[2m) // - Time: dim green (\x1b[32;2m) // - Punc: no colorization // - TextMarshaler: green (\x1b[32m) fmt.Printf("String color bytes: %v\n", clrs.String) fmt.Printf("Number color bytes: %v\n", clrs.Number) } ``` -------------------------------- ### CLI Tool for Colorized JSON Output Source: https://context7.com/neilotoole/jsoncolor/llms.txt A command-line interface tool demonstrating colorized JSON output with file I/O support. It uses flags for pretty printing, colorization, input/output files, and integrates with `go-colorable` for cross-platform compatibility. ```go package main import ( "flag" "fmt" "io" "io/ioutil" "os" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" ) var ( flagPretty = flag.Bool("p", true, "output pretty JSON") flagColorize = flag.Bool("c", true, "output colorized JSON") flagInput = flag.String("i", "", "input JSON file path") flagOutput = flag.String("o", "", "output file path") ) func main() { flag.Parse() // Read input var input []byte var err error if *flagInput != "" { input, err = ioutil.ReadFile(*flagInput) } else { input, err = ioutil.ReadAll(os.Stdin) } if err != nil { fmt.Fprintf(os.Stderr, "Error reading input: %v\n", err) os.Exit(1) } // Parse JSON var data interface{} if err := json.Unmarshal(input, &data); err != nil { fmt.Fprintf(os.Stderr, "Invalid JSON: %v\n", err) os.Exit(1) } // Setup output var out io.Writer = os.Stdout if *flagOutput != "" { f, err := os.Create(*flagOutput) if err != nil { fmt.Fprintf(os.Stderr, "Error creating output file: %v\n", err) os.Exit(1) } defer f.Close() out = f } // Create encoder with optional colorization var enc *json.Encoder if *flagColorize && *flagOutput == "" && json.IsColorTerminal(out) { out = colorable.NewColorable(out.(*os.File)) enc = json.NewEncoder(out) enc.SetColors(json.DefaultColors()) } else { enc = json.NewEncoder(out) } if *flagPretty { enc.SetIndent("", " ") } if err := enc.Encode(data); err != nil { fmt.Fprintf(os.Stderr, "Error encoding: %v\n", err) os.Exit(1) } } ``` -------------------------------- ### NewEncoder - Creating a JSON Encoder Source: https://context7.com/neilotoole/jsoncolor/llms.txt Demonstrates how to create a new JSON encoder with colorable output, enabling colorization and indentation. ```APIDOC ## NewEncoder Creates a new JSON encoder that writes to the specified writer. The encoder supports colorization via `SetColors()`, indentation via `SetIndent()`, and all standard encoding/json encoder options. ### Method ```go func NewEncoder(w io.Writer) *Encoder ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "os" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" ) func main() { // Create encoder with colorable output (needed for Windows compatibility) out := colorable.NewColorable(os.Stdout) enc := json.NewEncoder(out) // Enable colorization with jq-like default colors enc.SetColors(json.DefaultColors()) // Enable pretty-printing with 2-space indent enc.SetIndent("", " ") data := map[string]interface{}{ "name": "Alice", "age": 30, "active": true, "balance": nil, "tags": []string{"admin", "user"}, } if err := enc.Encode(data); err != nil { panic(err) } } ``` ### Response #### Success Response (200) None explicitly defined, but the encoder writes formatted JSON to the provided writer. #### Response Example ```json { "active": true, "age": 30, "balance": null, "name": "Alice", "tags": [ "admin", "user" ] } ``` ``` -------------------------------- ### Drop-in Replacement for encoding/json Source: https://github.com/neilotoole/jsoncolor/blob/master/README.md To use jsoncolor as a drop-in replacement for the standard library's encoding/json package, simply use an import alias. ```go import json "github.com/neilotoole/jsoncolor" ``` -------------------------------- ### SetColors - Customizing JSON Colors Source: https://context7.com/neilotoole/jsoncolor/llms.txt Explains how to configure the encoder to output colorized JSON with customizable colors for different JSON elements. ```APIDOC ## SetColors Configures the encoder to output colorized JSON. Pass a `*Colors` struct to enable colorization, or `nil` to disable it. Colors are specified using ANSI escape codes. ### Method ```go func (e *Encoder) SetColors(colors *Colors) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "os" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" ) func main() { out := colorable.NewColorable(os.Stdout) enc := json.NewEncoder(out) // Start with default jq-like colors clrs := json.DefaultColors() // Customize individual element colors using ANSI codes clrs.Key = json.Color("\x1b[34;1m") // Bold blue for keys clrs.String = json.Color("\x1b[32m") // Green for strings clrs.Number = json.Color("\x1b[36m") // Cyan for numbers clrs.Bool = json.Color("\x1b[33m") // Yellow for booleans clrs.Null = json.Color("\x1b[2m") // Dim for null clrs.Punc = json.Color{} // No color for punctuation (disable) enc.SetColors(clrs) enc.SetIndent("", " ") data := struct { ID int `json:"id"` Name string `json:"name"` Active bool `json:"active"` Profile *int `json:"profile"` }{ ID: 42, Name: "Test User", Active: true, Profile: nil, } enc.Encode(data) } ``` ### Response #### Success Response (200) None explicitly defined, but the encoder writes formatted JSON to the provided writer. #### Response Example (Output will be colorized JSON based on the `clrs` configuration) ``` -------------------------------- ### Customize JSON Output Colors with fatihcolor Source: https://context7.com/neilotoole/jsoncolor/llms.txt Integrate with fatih/color to customize JSON output colors. Use fatihcolor.DefaultColors() and then modify specific color attributes before converting to jsoncolor.Colors. ```go package main import ( "os" "github.com/fatih/color" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" "github.com/neilotoole/jsoncolor/helper/fatihcolor" ) func main() { out := colorable.NewColorable(os.Stdout) enc := json.NewEncoder(out) // Use fatihcolor for easier color configuration fclrs := fatihcolor.DefaultColors() // Customize using fatih/color's intuitive API fclrs.Key = color.New(color.FgMagenta, color.Bold) fclrs.String = color.New(color.FgCyan) fclrs.Number = color.New(color.FgYellow) fclrs.Bool = color.New(color.FgGreen, color.Bold) fclrs.Null = color.New(color.FgRed, color.Faint) fclrs.Punc = color.New(color.FgWhite) // Convert to core jsoncolor.Colors clrs := fatihcolor.ToCoreColors(fclrs) enc.SetColors(clrs) enc.SetIndent("", " ") data := map[string]interface{}{ "title": "Using fatih/color", "count": 42, "enabled": true, "disabled": false, "nothing": nil, "nested": map[string]interface{}{ "level": 2, }, } enc.Encode(data) } ``` -------------------------------- ### Serialize Go Values with Marshal and MarshalIndent Source: https://context7.com/neilotoole/jsoncolor/llms.txt These functions serve as drop-in replacements for standard library JSON serialization. Note that these do not produce colorized output. ```go package main import ( "fmt" json "github.com/neilotoole/jsoncolor" ) func main() { type User struct { ID int `json:"id"` Username string `json:"username"` Email string `json:"email,omitempty"` Roles []string `json:"roles"` CreatedAt string `json:"created_at"` } user := User{ ID: 1, Username: "johndoe", Roles: []string{"admin", "user"}, CreatedAt: "2024-01-15T10:30:00Z", } // Compact JSON (no indentation) compact, err := json.Marshal(user) if err != nil { panic(err) } fmt.Println("Compact:", string(compact)) // Pretty-printed JSON with indentation pretty, err := json.MarshalIndent(user, "", " ") if err != nil { panic(err) } fmt.Println("Pretty:\n", string(pretty)) } // Output: // Compact: {"id":1,"username":"johndoe","roles":["admin","user"],"created_at":"2024-01-15T10:30:00Z"} // Pretty: // { // "id": 1, // "username": "johndoe", // "roles": [ // "admin", // "user" // ], // "created_at": "2024-01-15T10:30:00Z" // } ``` -------------------------------- ### Configure custom colors with SetColors Source: https://context7.com/neilotoole/jsoncolor/llms.txt Customizes the appearance of JSON elements using ANSI escape codes. Pass nil to disable colorization entirely. ```go package main import ( "os" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" ) func main() { out := colorable.NewColorable(os.Stdout) enc := json.NewEncoder(out) // Start with default jq-like colors clrs := json.DefaultColors() // Customize individual element colors using ANSI codes clrs.Key = json.Color("\x1b[34;1m") // Bold blue for keys clrs.String = json.Color("\x1b[32m") // Green for strings clrs.Number = json.Color("\x1b[36m") // Cyan for numbers clrs.Bool = json.Color("\x1b[33m") // Yellow for booleans clrs.Null = json.Color("\x1b[2m") // Dim for null clrs.Punc = json.Color{} // No color for punctuation (disable) enc.SetColors(clrs) enc.SetIndent("", " ") data := struct { ID int `json:"id"` Name string `json:"name"` Active bool `json:"active"` Profile *int `json:"profile"` }{ ID: 42, Name: "Test User", Active: true, Profile: nil, } enc.Encode(data) } ``` -------------------------------- ### Default JSON Colors Configuration Source: https://github.com/neilotoole/jsoncolor/blob/master/README.md The DefaultColors function returns a Colors struct with default color settings similar to jq. Use Color{} to disable colorization for specific element types. ```go // DefaultColors returns the default Colors configuration. // These colors largely follow jq's default colorization, // with some deviation. func DefaultColors() *Colors { return &Colors{ Null: Color("\x1b[2m"), Bool: Color("\x1b[1m"), Number: Color("\x1b[36m"), String: Color("\x1b[32m"), Key: Color("\x1b[34;1m"), Bytes: Color("\x1b[2m"), Time: Color("\x1b[32;2m"), Punc: Color{}, // No colorization } } ``` -------------------------------- ### Create Streaming JSON Decoder Source: https://context7.com/neilotoole/jsoncolor/llms.txt Use NewDecoder to create a streaming JSON decoder from an io.Reader. Configure options like DisallowUnknownFields for stricter parsing. ```go package main import ( "fmt" "strings" json "github.com/neilotoole/jsoncolor" ) func main() { // Simulate streaming JSON (e.g., from HTTP response or file) jsonStream := ` {"name": "Alice", "score": 95} {"name": "Bob", "score": 87} {"name": "Charlie", "score": 92} ` type Result struct { Name string `json:"name"` Score int `json:"score"` } dec := json.NewDecoder(strings.NewReader(jsonStream)) // Optional: configure decoder behavior dec.DisallowUnknownFields() // Error on unknown JSON fields // dec.UseNumber() // Decode numbers as json.Number instead of float64 // dec.ZeroCopy() // Enable zero-copy optimizations var results []Result for { var r Result if err := dec.Decode(&r); err != nil { if err.Error() == "EOF" { break } panic(err) } results = append(results, r) fmt.Printf("Decoded at offset %d: %+v\n", dec.InputOffset(), r) } fmt.Printf("Total results: %d\n", len(results)) } ``` -------------------------------- ### Detect Terminal Color Support with IsColorTerminal Source: https://context7.com/neilotoole/jsoncolor/llms.txt Use this to check if a writer supports color output, respecting environment variables like NO_COLOR and FORCE_COLOR. ```go package main import ( "os" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" ) func main() { var enc *json.Encoder // Check if stdout supports color output if json.IsColorTerminal(os.Stdout) { // Terminal supports color - enable colorization out := colorable.NewColorable(os.Stdout) enc = json.NewEncoder(out) enc.SetColors(json.DefaultColors()) } else { // No color support (piped output, file, NO_COLOR set, etc.) enc = json.NewEncoder(os.Stdout) } enc.SetIndent("", " ") enc.Encode(map[string]interface{}{ "colorized": json.IsColorTerminal(os.Stdout), "message": "Hello, World!", }) } // Environment variable behavior: // - NO_COLOR="" (set): returns false // - FORCE_COLOR="" (set): returns true // - TERM=dumb: returns false ``` -------------------------------- ### Control Map Key Sorting in JSON Output Source: https://context7.com/neilotoole/jsoncolor/llms.txt Use `SetSortMapKeys` to control alphabetical sorting of map keys in JSON output. Enabled by default for deterministic results, disabling it can offer performance benefits for large maps by using iteration order. ```go package main import ( "bytes" "fmt" json "github.com/neilotoole/jsoncolor" ) func main() { data := map[string]int{ "zebra": 1, "apple": 2, "mango": 3, "banana": 4, } // With sorted keys (default) - deterministic output var sorted bytes.Buffer encSorted := json.NewEncoder(&sorted) encSorted.SetSortMapKeys(true) encSorted.SetIndent("", " ") encSorted.Encode(data) fmt.Println("Sorted keys:") fmt.Println(sorted.String()) // Without sorting - iteration order (faster for large maps) var unsorted bytes.Buffer encUnsorted := json.NewEncoder(&unsorted) encUnsorted.SetSortMapKeys(false) encUnsorted.SetIndent("", " ") encUnsorted.Encode(data) fmt.Println("Unsorted keys (order may vary):") fmt.Println(unsorted.String()) } ``` -------------------------------- ### Encode JSON with Color Source: https://github.com/neilotoole/jsoncolor/blob/master/README.md Encode a Go map to JSON with colorized output. It checks if the terminal supports color and uses colorable.NewColorable for Windows compatibility. Custom colors can be applied using enc.SetColors. ```go package main import ( "fmt" "github.com/mattn/go-colorable" json "github.com/neilotoole/jsoncolor" "os" ) func main() { var enc *json.Encoder // Note: this check will fail if running inside Goland (and // other IDEs?) as IsColorTerminal will return false. if json.IsColorTerminal(os.Stdout) { // Safe to use color out := colorable.NewColorable(os.Stdout) // needed for Windows enc = json.NewEncoder(out) // DefaultColors are similar to jq clrs := json.DefaultColors() // Change some values, just for fun clrs.Bool = json.Color("\x1b[36m") // Change the bool color clrs.String = json.Color{} // Disable the string color enc.SetColors(clrs) } else { // Can't use color; but the encoder will still work enc = json.NewEncoder(os.Stdout) } m := map[string]interface{}{ "a": 1, "b": true, "c": "hello", } if err := enc.Encode(m); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } ``` -------------------------------- ### Deserialize JSON with Unmarshal Source: https://context7.com/neilotoole/jsoncolor/llms.txt A drop-in replacement for encoding/json.Unmarshal that deserializes JSON bytes into Go structs or generic interfaces. ```go package main import ( "fmt" json "github.com/neilotoole/jsoncolor" ) func main() { jsonData := []byte(`{ "name": "Product A", "price": 29.99, "in_stock": true, "tags": ["electronics", "sale"], "metadata": null }`) // Unmarshal into a struct type Product struct { Name string `json:"name"` Price float64 `json:"price"` InStock bool `json:"in_stock"` Tags []string `json:"tags"` Metadata *string `json:"metadata"` } var product Product if err := json.Unmarshal(jsonData, &product); err != nil { panic(err) } fmt.Printf("Product: %+v\n", product) // Unmarshal into a generic interface{} var generic interface{} if err := json.Unmarshal(jsonData, &generic); err != nil { panic(err) } data := generic.(map[string]interface{}) fmt.Printf("Name: %s, Price: %.2f\n", data["name"], data["price"]) } // Output: // Product: {Name:Product A Price:29.99 InStock:true Tags:[electronics sale] Metadata:} // Name: Product A, Price: 29.99 ``` -------------------------------- ### Validate JSON Byte Slice Source: https://context7.com/neilotoole/jsoncolor/llms.txt Use the `Valid` function to check if a byte slice contains well-formed JSON. It returns `true` for valid JSON and `false` otherwise, handling cases like missing quotes or trailing commas. ```go package main import ( "fmt" json "github.com/neilotoole/jsoncolor" ) func main() { validJSON := []byte(`{"name": "test", "value": 123}`) invalidJSON := []byte(`{"name": "test", value: 123}`) // missing quotes emptyArray := []byte(`[]`) trailingComma := []byte(`{"a": 1,}`) fmt.Printf("Valid object: %v\n", json.Valid(validJSON)) fmt.Printf("Missing quotes: %v\n", json.Valid(invalidJSON)) fmt.Printf("Empty array: %v\n", json.Valid(emptyArray)) fmt.Printf("Trailing comma: %v\n", json.Valid(trailingComma)) } ``` -------------------------------- ### Control HTML Escaping in JSON Output Source: https://context7.com/neilotoole/jsoncolor/llms.txt Use SetEscapeHTML to control whether HTML-sensitive characters are escaped. Set to true (default) for security when embedding JSON in HTML, or false to preserve characters. ```go package main import ( "bytes" "fmt" json "github.com/neilotoole/jsoncolor" ) func main() { data := map[string]string{ "url": "https://example.com?a=1&b=2", "html": "", "safe": "No special characters", } // With HTML escaping (default) - safe for embedding in HTML var escaped bytes.Buffer encEscaped := json.NewEncoder(&escaped) encEscaped.SetEscapeHTML(true) // default encEscaped.Encode(data) fmt.Println("HTML Escaped:") fmt.Println(escaped.String()) // Without HTML escaping - preserves original characters var unescaped bytes.Buffer encUnescaped := json.NewEncoder(&unescaped) encUnescaped.SetEscapeHTML(false) encUnescaped.Encode(data) fmt.Println("Not Escaped:") fmt.Println(unescaped.String()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.