Skip to content

JSON Formatter — Go source

Beautify, minify and validate JSON instantly. Paste, format, copy - all in your browser. Share a link to your exact input.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// JSON formatter — parse, pretty-print (2-space indent), and minify.
//
// Language: Go
// CosmoDev polyglot showcase port of the `json-formatter` tool.
// Ported from src/tools/JsonFormatter.tsx — display source, part of CosmoDev's
// polyglot tool pages.
//
// Parses JSON with encoding/json, then re-emits it compact for "minify"
// (json.Marshal) or indented for "beautify" (json.MarshalIndent with the given
// indent, defaulting to two spaces to match the island). Parse errors surface
// err.Error(); empty/whitespace-only input yields empty output, no error.
//
// Parity caveats versus the TypeScript port: decoding into `any` round-trips
// every number through float64 (so integers beyond 2^53 lose precision, just
// as in JS), and Go's json package emits object keys in sorted order rather
// than preserving source order — object key order may therefore differ from
// the input even though the value is identical.
package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

// Mode selects the output shape.
type Mode int

const (
	ModeBeautify Mode = iota // indent with the given number of spaces
	ModeMinify               // compact, no whitespace
)

// Result mirrors the TypeScript { output, error } shape: an empty Error string
// means "no error".
type Result struct {
	Output string
	Error  string
}

// Format formats a JSON document the way the live island does. indent is the
// number of spaces per nesting level for ModeBeautify (pass 2 to match the UI).
//
//   - empty / whitespace-only input → empty output, no error
//   - valid JSON + ModeMinify   → compact JSON
//   - valid JSON + ModeBeautify → indent-space-indented JSON
//   - invalid JSON              → empty output, engine error message
func Format(input string, mode Mode, indent int) Result {
	if strings.TrimSpace(input) == "" {
		return Result{}
	}

	// Unmarshal into any: we only need to re-encode the value tree. Numbers
	// land as float64, objects as map[string]any (keys sorted on re-encode).
	var v any
	if err := json.Unmarshal([]byte(input), &v); err != nil {
		return Result{Error: err.Error()}
	}

	pad := strings.Repeat(" ", indent)
	var (
		out []byte
		err error
	)
	if mode == ModeMinify {
		out, err = json.Marshal(v)
	} else {
		out, err = json.MarshalIndent(v, "", pad)
	}
	if err != nil {
		return Result{Error: err.Error()}
	}
	return Result{Output: string(out)}
}

func main() {
	sample := `{"name":"CosmoDev","tools":["json","base64"],"free":true,"nested":{"ok":1}}`
	r := Format(sample, ModeBeautify, 2)
	if r.Error != "" {
		fmt.Println("error:", r.Error)
	} else {
		fmt.Println(r.Output)
	}
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →