Help us shape the future of Go! Take the 2026 Go Developer Survey

json

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

JSON Package

A comprehensive JSON utility package for the Gou framework, designed for the AI era with support for JSON, JSONC (JSON with Comments), YAML, and automatic repair of malformed JSON.

Features

  • Standard JSON Operations: Fast encoding/decoding using jsoniter
  • Universal Parser: Single Parse() function supporting JSON, JSONC, YAML with auto-detection
  • JSON Repair: Automatically fix malformed JSON from LLM outputs
  • Schema Validation: JSON Schema validation using draft 2020-12
  • Comment Support: Handle JSONC/Yao format (JSON with comments)

Go Usage

Basic Encoding/Decoding
import "github.com/yaoapp/gou/json"

// Encode to JSON string
data := map[string]interface{}{"name": "Alice", "age": 30}
jsonStr, err := json.Encode(data)

// Decode from JSON string
var result map[string]interface{}
err = json.Decode([]byte(jsonStr), &result)

// Decode with type inference
result, err := json.DecodeTyped([]byte(jsonStr))
Universal Parsing
// Auto-detect format (JSON, JSONC, YAML)
data, err := json.Parse(input)

// Parse with format hint
data, err := json.ParseWithHint(input, "yaml")

// Parse file
data, err := json.ParseFile("/path/to/file.yaml")

// Parse with type safety
var config Config
err := json.ParseTyped(input, &config)
JSON Repair
// Repair malformed JSON (useful for LLM outputs)
fixed, err := json.Repair(`{name: "Alice", age: 30, "incomplete": }`)
// Result: {"name": "Alice", "age": 30}
Comment Handling
// Remove comments from JSONC/Yao format
clean := json.TrimComments(`{
  // This is a comment
  "key": "value" /* block comment */
}`)
Schema Validation
// Create validator
validator, err := json.NewValidator(schemaJSON)

// Validate data
err = validator.Validate(data)

// One-shot validation
err = json.Validate(schemaJSON, data)

// Validate schema itself
err = json.ValidateSchema(schemaJSON)

JavaScript Usage (Yao Process)

All functions are available as Yao processes under the json.* namespace.

Basic Operations
// Encode to JSON
const jsonStr = Process("json.Encode", { name: "Alice", age: 30 });

// Decode from JSON
const data = Process("json.Decode", jsonStr);
Universal Parsing
// Auto-detect format
const data = Process("json.Parse", jsonString);

// Parse with hint
const data = Process("json.Parse", yamlString, "yaml");

// Parse file
const data = Process("json.ParseFile", "/data/config.yaml");
JSON Repair
// Repair malformed JSON from LLM
const fixed = Process("json.Repair", '{name: "Alice", incomplete: }');
Comment Handling
// Remove comments
const clean = Process("json.TrimComments", `{
  // Comment
  "key": "value"
}`);
Schema Validation
// Validate data against schema
const schema = {
  type: "object",
  properties: {
    name: { type: "string" },
    age: { type: "integer", minimum: 0 }
  },
  required: ["name"]
};

Process("json.Validate", schema, { name: "Alice", age: 30 });

// Validate schema itself
Process("json.ValidateSchema", schema);

Format Detection

The Parse() function automatically detects the input format:

  • JSON: Standard JSON syntax
  • JSONC: JSON with // or /* */ comments
  • YAML: YAML syntax (indentation-based)

You can also provide a hint ("json", "jsonc", "yao", "yaml") to skip auto-detection.

Performance Notes

  • Encode/Decode: Fast, optimized for performance (using jsoniter)
  • Parse: Comprehensive, supports multiple formats (slightly slower)
  • Repair: Designed for LLM outputs, may be slow on large inputs

Use Cases

  • AI/LLM Integration: Repair malformed JSON from language models
  • Configuration Files: Parse JSONC/YAML configs with comments
  • Schema Validation: Ensure data integrity for MCP tools/resources
  • Universal Parser: One function for all JSON-like formats

Backward Compatibility

For backward compatibility with Yao's utils.jsonschema.*, the following aliases are registered:

  • utils.jsonschema.Validate → json.Validate
  • utils.jsonschema.ValidateSchema → json.ValidateSchema

Testing

Run tests with coverage:

cd gou/json
go test -v -cover

Current coverage: 92.4%

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Decode

func Decode(data string) (interface{}, error)

Decode decodes JSON string to interface{}

func DecodeTyped

func DecodeTyped(data string, v interface{}) error

DecodeTyped decodes JSON string to the given typed pointer

func DetectFormat

func DetectFormat(data string) string

DetectFormat attempts to detect the format of the data Returns: "yaml", "json", "jsonc", or "" if uncertain

func Encode

func Encode(v interface{}) (string, error)

Encode encodes the given value to JSON string

func Parse

func Parse(data string, hint ...string) (interface{}, error)

Parse parses data in multiple formats (JSON, JSONC, Yao, YAML) with auto-repair Parameters:

  • data: the data string to parse
  • hint: optional format hint (e.g., "file.yaml", ".json", "yaml") If not provided, will attempt to auto-detect the format

func ParseFile

func ParseFile(filename string, data []byte, v interface{}) error

ParseFile parses data based on file extension Supports: .json, .jsonc, .yao, .yaml, .yml

func ParseTyped

func ParseTyped(data string, v interface{}, hint ...string) error

ParseTyped parses data into a typed pointer with format detection

func ProcessDecode

func ProcessDecode(process *process.Process) interface{}

ProcessDecode json.Decode Standard JSON decoding Args: data string - JSON string to decode Returns: decoded value

func ProcessEncode

func ProcessEncode(process *process.Process) interface{}

ProcessEncode json.Encode Standard JSON encoding Args: value interface{} - The value to encode Returns: JSON string

func ProcessParse

func ProcessParse(process *process.Process) interface{}

ProcessParse json.Parse Universal parser supporting JSON, JSONC, Yao, YAML with auto-repair Args:

  • data string - The data string to parse
  • hint string (optional) - Format hint (e.g., "file.yaml", ".json", "yaml")

Returns: parsed value

Usage:

// Parse JSON (with auto-repair if broken)
var data = Process("json.Parse", jsonString)

// Parse YAML
var data = Process("json.Parse", yamlString, "file.yaml")

// Parse Yao/JSONC (with comments)
var data = Process("json.Parse", yaoString, ".yao")

func ProcessRepair

func ProcessRepair(process *process.Process) interface{}

ProcessRepair json.Repair Repairs broken JSON Args: data string - Broken JSON string Returns: repaired JSON string

func ProcessValidate

func ProcessValidate(process *process.Process) interface{}

ProcessValidate json.Validate Validates data against a JSON Schema Args:

  • data interface{} - The data to validate
  • schema interface{} - The JSON Schema (map, string, or []byte)

Returns: nil if valid, error message string if invalid

Usage:

// Validate with schema map
var result = Process("json.Validate", data, schema)
if (result != null) {
    log.Error("Validation failed: " + result)
}

// Validate with JSON string
var schemaStr = '{"type": "object", "properties": {"name": {"type": "string"}}}'
var result = Process("json.Validate", {"name": "John"}, schemaStr)

func ProcessValidateSchema

func ProcessValidateSchema(process *process.Process) interface{}

ProcessValidateSchema json.ValidateSchema Validates a JSON Schema structure Args: schema interface{} - The JSON Schema to validate Returns: nil if valid, error message string if invalid

func Repair

func Repair(data string) (string, error)

Repair attempts to repair broken JSON

func TrimComments

func TrimComments(data []byte) []byte

TrimComments removes comments from JSONC/Yao format data Supports both single-line (//) and multi-line (/* */) comments

func Validate

func Validate(data interface{}, schema interface{}) error

Validate validates data against a JSON Schema (one-shot validation) Returns error if schema is invalid or data doesn't match the schema

Usage:

err := json.Validate(data, schemaMap)
if err != nil {
    log.Printf("Validation failed: %v", err)
}

func ValidateSchema

func ValidateSchema(schema interface{}) error

ValidateSchema validates a JSON Schema structure without compiling it Returns error if the schema is invalid

Types

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator wraps a compiled JSON Schema for validation

func NewValidator

func NewValidator(schema interface{}) (*Validator, error)

NewValidator compiles a JSON Schema and returns a validator Returns error if the schema is invalid

Args:

  • schema: can be map[string]interface{}, []byte, string, or any JSON-serializable type

Usage:

// From map
schemaMap := map[string]interface{}{
    "type": "object",
    "properties": map[string]interface{}{
        "name": map[string]interface{}{"type": "string"},
    },
    "required": []string{"name"},
}
validator, err := json.NewValidator(schemaMap)

// From JSON string
validator, err := json.NewValidator(`{"type": "object", "properties": {...}}`)

// From JSON bytes
validator, err := json.NewValidator([]byte(`{"type": "object", ...}`))

func (*Validator) Validate

func (v *Validator) Validate(data interface{}) error

Validate validates data against the compiled JSON Schema Returns nil if data is valid, error with validation details otherwise

Usage:

validator, _ := json.NewValidator(schemaMap)
data := map[string]interface{}{"name": "John"}
if err := validator.Validate(data); err != nil {
    log.Printf("Validation failed: %v", err)
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL