serdeval

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2025 License: MIT Imports: 16 Imported by: 0

README

SerdeVal

SerdeVal Banner Go Report Card Go Reference CI codecov Go Version License

A privacy-focused, blazingly fast data format validator supporting 14+ formats including JSON, YAML, XML, TOML, CSV, GraphQL, Markdown, and more.

Privacy-focused: All validation happens locally on your machine.

🌐 Live Demo

freedatavalidator.xyz - Try it online (client-side validation)

🚀 Features

  • 🔒 Privacy-First: No logging, tracking, or data retention
  • ⚡ Blazingly Fast: Zero-dependency Go implementation
  • 🎯 Auto-Detection: Automatically detects data formats
  • 📱 Multiple Interfaces: CLI, Go library, and web interface
  • 🌐 Cross-Platform: Windows, macOS, and Linux support
  • 🧠 Smart Formatting: Beautifies and validates in one step
  • 📊 Developer-Friendly: JSON output for CI/CD pipelines
Supported Formats
Format Extensions Auto-Detection Validation Use Case
JSON .json APIs, Config files
YAML .yaml, .yml Kubernetes, CI/CD
XML .xml Enterprise, SOAP
TOML .toml Config files
CSV .csv Data exchange
GraphQL .graphql, .gql API schemas
INI .ini, .cfg, .conf Config files
HCL .hcl, .tf, .tfvars Terraform
Protobuf .proto, .textproto Protocol Buffers
Markdown .md, .markdown Documentation
JSON Lines .jsonl, .ndjson Streaming data
Jupyter .ipynb Data science
Requirements.txt .txt Python deps
Dockerfile Dockerfile* Containers

📦 Installation

Using Go
# As a CLI tool
go install github.com/akhilesharora/serdeval/cmd/serdeval@latest

# As a library
go get github.com/akhilesharora/serdeval/pkg/validator
Pre-built Binaries

Download the latest binary for your platform from the releases page.

From Source
Linux/macOS
git clone https://github.com/akhilesharora/serdeval
cd serdeval
make build
Windows
git clone https://github.com/akhilesharora/serdeval
cd serdeval
go build -o serdeval.exe ./cmd/serdeval
Development Setup

For contributors, set up pre-commit hooks to ensure code quality:

# Install pre-commit hooks
make pre-commit

# Or manually
./scripts/setup-hooks.sh

This will install hooks that:

  • Format code automatically
  • Run tests before push
  • Check for linting issues
  • Prevent commits with formatting errors
Deployment

For server deployment, copy deploy.example.sh to deploy.sh and customize it with your specific configuration:

cp deploy.example.sh deploy.sh
# Edit deploy.sh with your server details

🖥️ Usage

Command Line Interface
Basic Usage
# Validate a single file (auto-detects format)
serdeval validate config.json

# Validate multiple files
serdeval validate config.json data.yaml settings.toml

# Validate from stdin
echo '{"name": "John", "age": 30}' | serdeval validate

# Specify format explicitly
serdeval validate --format json config.txt

# Output as JSON for CI/CD pipelines
serdeval validate --json config.json

# Start web interface
serdeval web --port 8080
Validate Each Format
# JSON files
serdeval validate package.json
serdeval validate data.json

# YAML files
serdeval validate docker-compose.yaml
serdeval validate config.yml

# XML files
serdeval validate pom.xml
serdeval validate web.xml

# TOML files
serdeval validate Cargo.toml
serdeval validate pyproject.toml

# CSV files
serdeval validate data.csv
serdeval validate report.csv

# GraphQL files
serdeval validate schema.graphql
serdeval validate query.gql

# INI/Config files
serdeval validate config.ini
serdeval validate settings.cfg
serdeval validate app.conf

# HCL/Terraform files
serdeval validate main.tf
serdeval validate variables.tfvars
serdeval validate config.hcl

# Protobuf text format
serdeval validate message.textproto
serdeval validate data.pbtxt

# Markdown files
serdeval validate README.md
serdeval validate docs.markdown

# JSON Lines files
serdeval validate logs.jsonl
serdeval validate events.ndjson

# Jupyter notebooks
serdeval validate analysis.ipynb

# Python requirements
serdeval validate requirements.txt
serdeval validate requirements-dev.txt

# Dockerfiles
serdeval validate Dockerfile
serdeval validate Dockerfile.prod
Go Library
Basic Usage
package main

import (
    "fmt"
    "log"
    
    "github.com/akhilesharora/serdeval/pkg/validator"
)

func main() {
    // Auto-detect format
    data := []byte(`{"name": "John", "age": 30}`)
    result := validator.ValidateAuto(data)
    
    if result.Valid {
        fmt.Printf("Valid %s data\n", result.Format)
    } else {
        log.Fatalf("Invalid data: %s", result.Error)
    }
}
Examples for Each Format
// JSON Validation
jsonValidator, _ := validator.NewValidator(validator.FormatJSON)
result := jsonValidator.ValidateString(`{"name": "test", "value": 123}`)
fmt.Printf("JSON valid: %v\n", result.Valid)

// YAML Validation
yamlValidator, _ := validator.NewValidator(validator.FormatYAML)
result = yamlValidator.ValidateString(`
name: test
value: 123
items:
  - one
  - two
`)
fmt.Printf("YAML valid: %v\n", result.Valid)

// XML Validation
xmlValidator, _ := validator.NewValidator(validator.FormatXML)
result = xmlValidator.ValidateString(`<?xml version="1.0"?>
<root>
  <name>test</name>
  <value>123</value>
</root>`)
fmt.Printf("XML valid: %v\n", result.Valid)

// TOML Validation
tomlValidator, _ := validator.NewValidator(validator.FormatTOML)
result = tomlValidator.ValidateString(`
[server]
host = "localhost"
port = 8080
`)
fmt.Printf("TOML valid: %v\n", result.Valid)

// CSV Validation
csvValidator, _ := validator.NewValidator(validator.FormatCSV)
result = csvValidator.ValidateString(`name,age,city
John,30,NYC
Jane,25,LA`)
fmt.Printf("CSV valid: %v\n", result.Valid)

// GraphQL Validation
graphqlValidator, _ := validator.NewValidator(validator.FormatGraphQL)
result = graphqlValidator.ValidateString(`
query GetUser {
  user(id: "123") {
    name
    email
  }
}`)
fmt.Printf("GraphQL valid: %v\n", result.Valid)

// INI Validation
iniValidator, _ := validator.NewValidator(validator.FormatINI)
result = iniValidator.ValidateString(`
[database]
host = localhost
port = 5432
`)
fmt.Printf("INI valid: %v\n", result.Valid)

// HCL Validation
hclValidator, _ := validator.NewValidator(validator.FormatHCL)
result = hclValidator.ValidateString(`
resource "aws_instance" "example" {
  ami           = "ami-12345"
  instance_type = "t2.micro"
}`)
fmt.Printf("HCL valid: %v\n", result.Valid)

// Protobuf Text Validation
protoValidator, _ := validator.NewValidator(validator.FormatProtobuf)
result = protoValidator.ValidateString(`
type_url: "type.googleapis.com/example"
value: "\n\x05hello"
`)
fmt.Printf("Protobuf valid: %v\n", result.Valid)

// Markdown Validation
mdValidator, _ := validator.NewValidator(validator.FormatMarkdown)
result = mdValidator.ValidateString(`# Title

This is **bold** text.

- Item 1
- Item 2
`)
fmt.Printf("Markdown valid: %v\n", result.Valid)

// JSON Lines Validation
jsonlValidator, _ := validator.NewValidator(validator.FormatJSONL)
result = jsonlValidator.ValidateString(`{"event": "login", "user": "john"}
{"event": "logout", "user": "john"}
{"event": "login", "user": "jane"}`)
fmt.Printf("JSONL valid: %v\n", result.Valid)

// Jupyter Notebook Validation
jupyterValidator, _ := validator.NewValidator(validator.FormatJupyter)
result = jupyterValidator.ValidateString(`{
  "cells": [],
  "metadata": {"kernelspec": {"name": "python3"}},
  "nbformat": 4,
  "nbformat_minor": 2
}`)
fmt.Printf("Jupyter valid: %v\n", result.Valid)

// Requirements.txt Validation
reqValidator, _ := validator.NewValidator(validator.FormatRequirements)
result = reqValidator.ValidateString(`numpy==1.21.0
pandas>=1.3.0
scikit-learn~=1.0.0`)
fmt.Printf("Requirements valid: %v\n", result.Valid)

// Dockerfile Validation
dockerValidator, _ := validator.NewValidator(validator.FormatDockerfile)
result = dockerValidator.ValidateString(`FROM python:3.9
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "app.py"]`)
fmt.Printf("Dockerfile valid: %v\n", result.Valid)
Web Interface

Start the built-in web server:

serdeval web --port 8080

Then visit http://localhost:8080 for a user-friendly interface with:

  • Real-time validation as you type
  • Auto-format with beautification
  • Copy-to-clipboard functionality
  • Format auto-detection
  • 100% client-side processing (your data never leaves your browser)

🛠️ Development

Prerequisites
  • Go 1.22 or higher
  • Make (optional, for convenience commands)
Building
# Build for current platform
make build

# Build for all platforms
make build-all

# Run tests
make test

# Run linters
make lint

# Format code
make fmt

# Run benchmarks
make bench
Testing
# Run all tests
go test ./...

# Run tests with coverage
go test -coverprofile=coverage.out ./...

# Run benchmarks
go test -bench=. ./...

🤝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

Quick Start for Contributors
  1. Fork the repository
  2. Set up development environment: make pre-commit
  3. Make your changes
  4. Run tests: make test
  5. Submit a pull request

Please read our Code of Conduct.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Built with ❤️ for the developer community
  • Inspired by the need for privacy-focused validation tools
  • Thanks to all contributors who help improve this project

Visit SerdeVal | Documentation | Report Issues

Documentation

Overview

Package validator provides comprehensive data format validation for Go applications.

The validator package supports validation of multiple data formats including JSON, YAML, XML, TOML, CSV, GraphQL, INI, HCL, Protobuf text format, Markdown, JSON Lines, Jupyter Notebooks, Python requirements.txt, and Dockerfiles. It features automatic format detection and a unified API for all supported formats.

Features

  • Support for 15+ data formats
  • Automatic format detection from content or filename
  • Zero dependencies for core validation logic
  • Thread-safe validator implementations
  • Simple, consistent API across all formats
  • Privacy-focused: no logging, network calls, or data retention
  • Comprehensive error messages for validation failures

Basic Usage

Create a validator for a specific format:

import "github.com/akhilesharora/serdeval"

// Create a JSON validator
v, err := serdeval.NewValidator(serdeval.FormatJSON)
if err != nil {
	log.Fatal(err)
}

// Validate a string
result := v.ValidateString(`{"name": "test", "value": 123}`)
if result.Valid {
	fmt.Println("Valid JSON!")
} else {
	fmt.Printf("Invalid JSON: %s\n", result.Error)
}

Automatic Format Detection

Use ValidateAuto for automatic format detection:

data := []byte(`{"key": "value"}`)
result := serdeval.ValidateAuto(data)
fmt.Printf("Detected format: %s\n", result.Format)
fmt.Printf("Valid: %v\n", result.Valid)

Detect format from filename:

format := serdeval.DetectFormatFromFilename("config.yaml")
// format == serdeval.FormatYAML

Supported Formats

The package supports the following formats:

  • JSON (FormatJSON): RFC 7159 compliant JSON validation
  • YAML (FormatYAML): YAML 1.2 specification
  • XML (FormatXML): Well-formed XML validation
  • TOML (FormatTOML): TOML v1.0.0 format
  • CSV (FormatCSV): Comma-separated values with consistent columns
  • GraphQL (FormatGraphQL): GraphQL queries, mutations, and schemas
  • INI (FormatINI): INI configuration files with sections
  • HCL (FormatHCL): HashiCorp Configuration Language (HCL2)
  • Protobuf (FormatProtobuf): Protocol Buffers text format
  • Markdown (FormatMarkdown): CommonMark specification
  • JSON Lines (FormatJSONL): Newline-delimited JSON
  • Jupyter (FormatJupyter): Jupyter Notebook .ipynb files
  • Requirements (FormatRequirements): Python requirements.txt
  • Dockerfile (FormatDockerfile): Docker container definitions

Advanced Usage

Validate multiple files with different formats:

files := []string{"config.json", "data.yaml", "schema.graphql"}

for _, file := range files {
	data, err := os.ReadFile(file)
	if err != nil {
		log.Printf("Error reading %s: %v", file, err)
		continue
	}

	// Detect format from filename
	format := serdeval.DetectFormatFromFilename(file)
	if format == serdeval.FormatUnknown {
		// Fall back to content detection
		format = serdeval.DetectFormat(data)
	}

	// Create appropriate validator
	v, err := serdeval.NewValidator(format)
	if err != nil {
		log.Printf("Unsupported format for %s", file)
		continue
	}

	// Validate the file
	result := v.Validate(data)
	result.FileName = file

	if result.Valid {
		fmt.Printf("✓ %s: Valid %s\n", file, result.Format)
	} else {
		fmt.Printf("✗ %s: %s\n", file, result.Error)
	}
}

Format Detection Heuristics

The package uses intelligent heuristics for format detection:

  • File extension matching for reliable format identification
  • Content-based detection using format-specific patterns
  • Precedence given to more specific formats (e.g., Jupyter over JSON)
  • Support for files without extensions (e.g., Dockerfile)

Privacy and Security

This package is designed with privacy and security in mind:

  • All validation is performed in-memory
  • No network connections are made
  • No temporary files are created
  • No data is logged or retained
  • Input data is never modified

Thread Safety

All validator implementations are thread-safe and can be reused across multiple goroutines:

validator, _ := serdeval.NewValidator(serdeval.FormatJSON)

// Safe to use concurrently
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
	wg.Add(1)
	go func(data string) {
		defer wg.Done()
		result := serdeval.ValidateString(data)
		// Process result
	}(jsonData[i])
}
wg.Wait()

Error Handling

Validation errors include detailed information about what went wrong:

result := serdeval.ValidateString(invalidJSON)
if !result.Valid {
	// result.Error contains specific error message
	// e.g., "unexpected end of JSON input"
	fmt.Printf("Validation failed: %s\n", result.Error)
}

Package serdeval provides data format validation for JSON, YAML, XML, TOML, CSV, GraphQL, INI, HCL, Protobuf text format, Markdown, JSON Lines, Jupyter Notebooks, Requirements.txt, and Dockerfile

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CSVValidator

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

CSVValidator validates CSV (Comma-Separated Values) data. It checks that the data can be parsed as valid CSV with consistent column counts.

Example:

validator := &CSVValidator{baseValidator{format: FormatCSV}}
result := validator.ValidateString("name,age\nJohn,30\nJane,25")

func (CSVValidator) Format

func (v CSVValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*CSVValidator) Validate

func (v *CSVValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid CSV data. It reads all records to ensure consistent column counts and proper formatting.

Example:

validator := &CSVValidator{baseValidator{format: FormatCSV}}
result := validator.Validate([]byte("name,age\nJohn,30"))

func (*CSVValidator) ValidateString

func (v *CSVValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a CSV string. It converts the string to bytes and calls Validate.

Example:

validator := &CSVValidator{baseValidator{format: FormatCSV}}
result := validator.ValidateString("header1,header2\nvalue1,value2")

type DockerfileValidator

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

DockerfileValidator validates Dockerfile syntax. It checks for valid Docker instructions and ensures at least one FROM instruction exists.

Example:

validator := &DockerfileValidator{baseValidator{format: FormatDockerfile}}
result := validator.ValidateString("FROM golang:1.19\nWORKDIR /app\nCOPY . .")

func (DockerfileValidator) Format

func (v DockerfileValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*DockerfileValidator) Validate

func (v *DockerfileValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid Dockerfile syntax. It verifies that valid Docker instructions are used and at least one FROM instruction exists. Line continuations with backslash are supported.

Example:

validator := &DockerfileValidator{baseValidator{format: FormatDockerfile}}
result := validator.Validate([]byte("FROM alpine:latest\nRUN apk add --no-cache curl"))

func (*DockerfileValidator) ValidateString

func (v *DockerfileValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a Dockerfile string. It converts the string to bytes and calls Validate.

Example:

validator := &DockerfileValidator{baseValidator{format: FormatDockerfile}}
result := validator.ValidateString("FROM node:16\nWORKDIR /app\nCOPY . .")

type Format

type Format string

Format represents a supported data format type. It is used to specify which validator to use and identify detected formats.

const (
	// FormatJSON represents JSON format
	FormatJSON Format = "json"
	// FormatYAML represents YAML format
	FormatYAML Format = "yaml"
	// FormatXML represents XML format
	FormatXML Format = "xml"
	// FormatTOML represents TOML format
	FormatTOML Format = "toml"
	// FormatCSV represents CSV format
	FormatCSV Format = "csv"
	// FormatGraphQL represents GraphQL query/schema format
	FormatGraphQL Format = "graphql"
	// FormatINI represents INI configuration format
	FormatINI Format = "ini"
	// FormatHCL represents HCL (HashiCorp Configuration Language) format
	FormatHCL Format = "hcl"
	// FormatProtobuf represents Protobuf text format
	FormatProtobuf Format = "protobuf"
	// FormatMarkdown represents Markdown format
	FormatMarkdown Format = "markdown"
	// FormatJSONL represents JSON Lines format (newline-delimited JSON)
	FormatJSONL Format = "jsonl"
	// FormatJupyter represents Jupyter Notebook format
	FormatJupyter Format = "jupyter"
	// FormatRequirements represents Requirements.txt format
	FormatRequirements Format = "requirements"
	// FormatDockerfile represents Dockerfile format
	FormatDockerfile Format = "dockerfile"
	// FormatAuto represents automatic format detection
	FormatAuto Format = "auto"
	// FormatUnknown represents unknown format
	FormatUnknown Format = "unknown"
)

func DetectFormat

func DetectFormat(data []byte) Format

DetectFormat attempts to detect the data format by analyzing the content. Uses simple heuristics to identify various data formats.

Detection rules:

  • JSON: Starts with '{' or '['
  • XML: Starts with '<?xml' or '<'
  • YAML: Contains '---' or has key:value pattern
  • TOML: Contains '[section]' pattern with key=value pairs
  • CSV: Has comma-separated values with consistent columns
  • GraphQL: Contains query/mutation/type/schema keywords
  • INI: Has [section] headers or key=value pairs
  • Dockerfile: Starts with FROM instruction
  • Markdown: Contains markdown syntax like #, *, -, ```
  • Requirements.txt: Contains package names with version specifiers

Returns FormatUnknown if the format cannot be determined.

func DetectFormatFromFilename

func DetectFormatFromFilename(filename string) Format

DetectFormatFromFilename attempts to detect format from filename extension.

Supported extensions:

  • .json → FormatJSON
  • .yaml, .yml → FormatYAML
  • .xml → FormatXML
  • .toml → FormatTOML

Example:

format := DetectFormatFromFilename("config.json")
// format == FormatJSON

Returns FormatUnknown if the extension is not recognized.

type GraphQLValidator

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

GraphQLValidator validates GraphQL queries, mutations, subscriptions, and schema definitions. It uses the GraphQL parser to ensure syntactic validity.

Example:

validator := &GraphQLValidator{baseValidator{format: FormatGraphQL}}
result := validator.ValidateString(`query { user(id: "123") { name email } }`)

func (GraphQLValidator) Format

func (v GraphQLValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*GraphQLValidator) Validate

func (v *GraphQLValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid GraphQL syntax. It can validate queries, mutations, subscriptions, and schema definitions. Empty content is considered invalid.

Example:

validator := &GraphQLValidator{baseValidator{format: FormatGraphQL}}
result := validator.Validate([]byte(`query { user { name } }`))

func (*GraphQLValidator) ValidateString

func (v *GraphQLValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a GraphQL string. It converts the string to bytes and calls Validate.

Example:

validator := &GraphQLValidator{baseValidator{format: FormatGraphQL}}
result := validator.ValidateString(`mutation { createUser(name: "John") { id } }`)

type HCLValidator

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

HCLValidator validates HCL (HashiCorp Configuration Language) data. It supports HCL2 syntax used in Terraform, Packer, and other HashiCorp tools.

Example:

validator := &HCLValidator{baseValidator{format: FormatHCL}}
result := validator.ValidateString(`resource "aws_instance" "example" { ami = "ami-123" }`)

func (HCLValidator) Format

func (v HCLValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*HCLValidator) Validate

func (v *HCLValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid HCL2 syntax. It uses the HashiCorp HCL parser to validate the configuration.

Example:

validator := &HCLValidator{baseValidator{format: FormatHCL}}
result := validator.Validate([]byte(`variable "region" { default = "us-west-2" }`))

func (*HCLValidator) ValidateString

func (v *HCLValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates an HCL string. It converts the string to bytes and calls Validate.

Example:

validator := &HCLValidator{baseValidator{format: FormatHCL}}
result := validator.ValidateString(`resource "aws_instance" "web" { ami = "ami-123" }`)

type INIValidator

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

INIValidator validates INI configuration file format. It supports sections, key-value pairs, and comments.

Example:

validator := &INIValidator{baseValidator{format: FormatINI}}
result := validator.ValidateString(`[database]\nhost = localhost\nport = 5432`)

func (INIValidator) Format

func (v INIValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*INIValidator) Validate

func (v *INIValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid INI format data. It supports sections, key-value pairs, and comments.

Example:

validator := &INIValidator{baseValidator{format: FormatINI}}
result := validator.Validate([]byte(`[section]\nkey = value`))

func (*INIValidator) ValidateString

func (v *INIValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates an INI string. It converts the string to bytes and calls Validate.

Example:

validator := &INIValidator{baseValidator{format: FormatINI}}
result := validator.ValidateString("[database]\nhost = localhost")

type JSONLValidator

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

JSONLValidator validates JSON Lines (newline-delimited JSON) data. Each line must be a valid JSON object or array.

Example:

validator := &JSONLValidator{baseValidator{format: FormatJSONL}}
result := validator.ValidateString(`{"name": "John"}\n{"name": "Jane"}`)

func (JSONLValidator) Format

func (v JSONLValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*JSONLValidator) Validate

func (v *JSONLValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid JSON Lines format. Each non-empty line must be a valid JSON object or array. Empty lines are allowed and ignored.

Example:

validator := &JSONLValidator{baseValidator{format: FormatJSONL}}
result := validator.Validate([]byte(`{"id":1}\n{"id":2}`))

func (*JSONLValidator) ValidateString

func (v *JSONLValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a JSON Lines string. It converts the string to bytes and calls Validate.

Example:

validator := &JSONLValidator{baseValidator{format: FormatJSONL}}
result := validator.ValidateString(`{"event":"start"}\n{"event":"end"}`)

type JSONValidator

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

JSONValidator validates JSON data according to RFC 7159. It supports validation of both JSON objects and arrays.

Example:

validator := &JSONValidator{baseValidator{format: FormatJSON}}
result := validator.ValidateString(`{"name": "test", "value": 123}`)

func (JSONValidator) Format

func (v JSONValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*JSONValidator) Validate

func (v *JSONValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid JSON data. It attempts to unmarshal the data and returns a Result indicating success or failure.

The validation checks for proper JSON syntax including:

  • Matching braces and brackets
  • Proper string escaping
  • Valid number formats
  • Correct use of null, true, and false

Example:

validator := &JSONValidator{baseValidator{format: FormatJSON}}
result := validator.Validate([]byte(`{"valid": true}`))
if result.Valid {
	fmt.Println("Valid JSON!")
}

func (*JSONValidator) ValidateString

func (v *JSONValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a JSON string. It converts the string to bytes and calls Validate.

Example:

validator := &JSONValidator{baseValidator{format: FormatJSON}}
result := validator.ValidateString(`{"name": "test"}`)

type JupyterValidator

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

JupyterValidator validates Jupyter Notebook (.ipynb) files. It checks for the required notebook structure including cells, metadata, and nbformat.

Example:

validator := &JupyterValidator{baseValidator{format: FormatJupyter}}
result := validator.Validate(jupyterNotebookBytes)

func (JupyterValidator) Format

func (v JupyterValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*JupyterValidator) Validate

func (v *JupyterValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains a valid Jupyter Notebook. It verifies that the data is valid JSON and contains required notebook fields: cells, metadata, and nbformat.

Example:

validator := &JupyterValidator{baseValidator{format: FormatJupyter}}
notebookData, _ := os.ReadFile("notebook.ipynb")
result := validator.Validate(notebookData)

func (*JupyterValidator) ValidateString

func (v *JupyterValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a Jupyter Notebook string. It converts the string to bytes and calls Validate.

Example:

validator := &JupyterValidator{baseValidator{format: FormatJupyter}}
result := validator.ValidateString(notebookJSONString)

type MarkdownValidator

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

MarkdownValidator validates Markdown formatted text. It uses the CommonMark specification to parse and validate the content.

Example:

validator := &MarkdownValidator{baseValidator{format: FormatMarkdown}}
result := validator.ValidateString("# Title\n\nThis is **bold** text.")

func (MarkdownValidator) Format

func (v MarkdownValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*MarkdownValidator) Validate

func (v *MarkdownValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid Markdown. It uses the CommonMark specification to parse the content.

Example:

validator := &MarkdownValidator{baseValidator{format: FormatMarkdown}}
result := validator.Validate([]byte("# Title\n\nParagraph with **bold** text."))

func (*MarkdownValidator) ValidateString

func (v *MarkdownValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a Markdown string. It converts the string to bytes and calls Validate.

Example:

validator := &MarkdownValidator{baseValidator{format: FormatMarkdown}}
result := validator.ValidateString("## Heading\n\n- List item 1\n- List item 2")

type ProtobufValidator

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

ProtobufValidator validates Protocol Buffers text format data. It checks that the data can be parsed as valid protobuf text format.

Example:

validator := &ProtobufValidator{baseValidator{format: FormatProtobuf}}
result := validator.ValidateString(`type_url: "type.googleapis.com/Example" value: "\x08\x01"`)

func (ProtobufValidator) Format

func (v ProtobufValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*ProtobufValidator) Validate

func (v *ProtobufValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid Protocol Buffers text format. It attempts to unmarshal the data as protobuf text format.

Example:

validator := &ProtobufValidator{baseValidator{format: FormatProtobuf}}
result := validator.Validate([]byte(`type_url: "example.com/Type"`))

func (*ProtobufValidator) ValidateString

func (v *ProtobufValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a Protobuf text format string. It converts the string to bytes and calls Validate.

Example:

validator := &ProtobufValidator{baseValidator{format: FormatProtobuf}}
result := validator.ValidateString(`type_url: "type.googleapis.com/Example"`)

type RequirementsValidator

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

RequirementsValidator validates Python requirements.txt file format. It supports package names with version specifiers (==, >=, <=, ~=) and comments.

Example:

validator := &RequirementsValidator{baseValidator{format: FormatRequirements}}
result := validator.ValidateString("flask==2.0.1\nrequests>=2.25.0")

func (RequirementsValidator) Format

func (v RequirementsValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*RequirementsValidator) Validate

func (v *RequirementsValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid requirements.txt format. It supports package names with version specifiers and comments. Empty lines and lines starting with # are allowed.

Example:

validator := &RequirementsValidator{baseValidator{format: FormatRequirements}}
result := validator.Validate([]byte("django==3.2\nrequests>=2.25.0"))

func (*RequirementsValidator) ValidateString

func (v *RequirementsValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a requirements.txt string. It converts the string to bytes and calls Validate.

Example:

validator := &RequirementsValidator{baseValidator{format: FormatRequirements}}
result := validator.ValidateString("numpy>=1.19.0\npandas==1.3.0")

type Result

type Result struct {
	// Valid indicates whether the data is valid for the detected/specified format
	Valid bool `json:"valid"`
	// Format indicates the data format that was validated
	Format Format `json:"format"`
	// Error contains the validation error message if Valid is false
	Error string `json:"error,omitempty"`
	// FileName is an optional field to track which file was validated
	FileName string `json:"filename,omitempty"`
}

Result contains the validation result for a data format validation operation. It provides information about whether the validation succeeded, the format that was validated, and any error messages if validation failed.

Example:

result := validator.ValidateString(`{"key": "value"}`)
if result.Valid {
	fmt.Printf("Valid %s data\n", result.Format)
} else {
	fmt.Printf("Invalid data: %s\n", result.Error)
}

func ValidateAuto

func ValidateAuto(data []byte) Result

ValidateAuto validates data with automatic format detection. It first attempts to detect the format, then validates using the appropriate validator.

Example:

data := []byte(`{"name": "test"}`)
result := ValidateAuto(data)
fmt.Printf("Format: %s, Valid: %v\n", result.Format, result.Valid)
// Output: Format: json, Valid: true

Returns a Result with Format=FormatUnknown if the format cannot be detected.

type TOMLValidator

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

TOMLValidator validates TOML (Tom's Obvious, Minimal Language) data. It supports all TOML v1.0.0 features including tables, arrays, and inline tables.

Example:

validator := &TOMLValidator{baseValidator{format: FormatTOML}}
result := validator.ValidateString(`[server]\nhost = "localhost"\nport = 8080`)

func (TOMLValidator) Format

func (v TOMLValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*TOMLValidator) Validate

func (v *TOMLValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid TOML data. It supports all TOML v1.0.0 features.

Example:

validator := &TOMLValidator{baseValidator{format: FormatTOML}}
result := validator.Validate([]byte(`[server]\nport = 8080`))

func (*TOMLValidator) ValidateString

func (v *TOMLValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a TOML string. It converts the string to bytes and calls Validate.

Example:

validator := &TOMLValidator{baseValidator{format: FormatTOML}}
result := validator.ValidateString(`title = "TOML Example"`)

type Validator

type Validator interface {
	// Validate checks if the provided byte slice is valid for this validator's format.
	// Returns a Result containing validation status and any error messages.
	Validate(data []byte) Result

	// ValidateString is a convenience method that validates a string.
	// Internally converts the string to []byte and calls Validate.
	ValidateString(data string) Result

	// Format returns the data format this validator is configured for.
	Format() Format
}

Validator is the main interface for validating data formats. Each validator implementation is specific to a single format.

Implementations are thread-safe and can be reused for multiple validations.

Example:

validator, err := NewValidator(FormatJSON)
if err != nil {
	log.Fatal(err)
}

// Validate bytes
result := validator.Validate(jsonBytes)

// Or validate string
result := validator.ValidateString(jsonString)

func NewValidator

func NewValidator(format Format) (Validator, error)

NewValidator creates a new validator for the specified format.

Example:

validator, err := NewValidator(FormatJSON)
if err != nil {
	log.Fatal(err)
}
result := validator.ValidateString(`{"key": "value"}`)
if result.Valid {
	fmt.Println("Valid JSON!")
}

Supported formats: FormatJSON, FormatYAML, FormatXML, FormatTOML, FormatCSV, FormatGraphQL, FormatINI, FormatHCL, FormatProtobuf, FormatMarkdown, FormatJSONL, FormatJupyter, FormatRequirements, FormatDockerfile Returns an error if an unsupported format is specified.

type XMLValidator

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

XMLValidator validates XML data for well-formedness. It checks that the XML is properly structured with matching tags and valid syntax.

Note: This validator checks for well-formedness only, not validity against a schema.

Example:

validator := &XMLValidator{baseValidator{format: FormatXML}}
result := validator.ValidateString(`<root><item>test</item></root>`)

func (XMLValidator) Format

func (v XMLValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*XMLValidator) Validate

func (v *XMLValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains well-formed XML data. Note that this only checks for well-formedness, not validity against a schema.

Example:

validator := &XMLValidator{baseValidator{format: FormatXML}}
result := validator.Validate([]byte(`<?xml version="1.0"?><root></root>`))

func (*XMLValidator) ValidateString

func (v *XMLValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates an XML string. It converts the string to bytes and calls Validate.

Example:

validator := &XMLValidator{baseValidator{format: FormatXML}}
result := validator.ValidateString(`<root><item>test</item></root>`)

type YAMLValidator

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

YAMLValidator validates YAML data according to YAML 1.2 specification. It supports all standard YAML features including anchors, aliases, and multi-document streams.

Example:

validator := &YAMLValidator{baseValidator{format: FormatYAML}}
result := validator.ValidateString("name: test\nvalue: 123")

func (YAMLValidator) Format

func (v YAMLValidator) Format() Format

Format returns the data format type associated with this validator. This method is available on all validator implementations.

Example:

validator, _ := NewValidator(FormatJSON)
fmt.Println(validator.Format()) // Output: json

func (*YAMLValidator) Validate

func (v *YAMLValidator) Validate(data []byte) Result

Validate checks if the provided byte slice contains valid YAML data. It supports all YAML 1.2 features including multi-document streams.

Example:

validator := &YAMLValidator{baseValidator{format: FormatYAML}}
result := validator.Validate([]byte("key: value\nlist:\n  - item1\n  - item2"))

func (*YAMLValidator) ValidateString

func (v *YAMLValidator) ValidateString(data string) Result

ValidateString is a convenience method that validates a YAML string. It converts the string to bytes and calls Validate.

Example:

validator := &YAMLValidator{baseValidator{format: FormatYAML}}
result := validator.ValidateString("name: test\nvalue: 123")

Directories

Path Synopsis
cmd
serdeval command
Command serdeval provides a CLI for validating JSON, YAML, XML, and TOML files.
Command serdeval provides a CLI for validating JSON, YAML, XML, and TOML files.

Jump to

Keyboard shortcuts

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