Skip to content

JSON Tree Explorer — Go source

Paste JSON and explore it as a navigable tree: every node with its path, type, and value preview. Filter by key, path, or value — ancestors of matches stay visible — with live type counts for the whole document.

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

// Package jsontree is the Go twin of CosmoDev's src/lib/json-tree.ts (dual
// source: the web lib is TypeScript, the CLI lib is Go — kept in lock-step).
// Pure + deterministic, never panics. The table-driven tests in
// json-tree_test.go share vectors with src/lib/json-tree.test.ts so the two
// implementations are held to the same contract.
//
// The island renders these rows; the Go twin reproduces flatten/filter/counts
// deterministically: preorder walk in document order, paths as $.a[0].b,
// primitives carry a preview string, and filter matching is a case-insensitive
// substring test on key, path, and stringified value — never on type names
// alone.
//
// Document key order is the hard requirement: encoding/json unmarshals objects
// into maps, which loses insertion order. ParseJson therefore walks the raw
// bytes with a json.Decoder Token() stream and builds an ordered JsonNode tree,
// so FlattenJson emits children in the order they appear in the document —
// exactly like the TS lib's Object.entries walk.
package jsontree

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

// JsonNodeType is the JSON type of a row, spelled exactly as in the TS lib
// ('object' | 'array' | 'string' | 'number' | 'boolean' | 'null').
type JsonNodeType string

const (
	TypeObject  JsonNodeType = "object"
	TypeArray   JsonNodeType = "array"
	TypeString  JsonNodeType = "string"
	TypeNumber  JsonNodeType = "number"
	TypeBoolean JsonNodeType = "boolean"
	TypeNull    JsonNodeType = "null"
)

// TreeRow is one flattened node. Path doubles as the stable row id (the TS
// lib's id field is the path itself, so the Go twin omits the duplicate).
type TreeRow struct {
	// Path is the JSONPath-style path: $, $.a, $.a[0], $.a[0].b.
	Path string
	// Key is the last path segment; '' for the root row.
	Key string
	// Depth is 0 for the root row.
	Depth int
	// Type is the JSON type of the node.
	Type JsonNodeType
	// Preview is set for primitives only (strings unquoted, truncated at 80
	// runes); nil for object/array rows, mirroring the TS null.
	Preview *string
	// ChildCount is set for object/array rows (number of direct children);
	// nil for primitives, mirroring the TS null.
	ChildCount *int
}

// JsonMember is one ordered object entry.
type JsonMember struct {
	Key   string
	Value *JsonNode
}

// JsonNode is a JSON value that remembers document order. It is what
// encoding/json's map-based unmarshal cannot give us.
type JsonNode struct {
	Type JsonNodeType
	// Str is the decoded string value (TypeString).
	Str string
	// Num is the raw number literal as it appeared in the document
	// (TypeNumber), the "source-ish" form TS previews via String(v).
	Num string
	// Bool is the boolean value (TypeBoolean).
	Bool bool
	// Members are object entries in document order (TypeObject).
	Members []JsonMember
	// Items are array elements in document order (TypeArray).
	Items []*JsonNode
}

// strPtr / intPtr build the nullable TreeRow fields.
func strPtr(s string) *string { return &s }
func intPtr(i int) *int       { return &i }

// ParseJson parses raw JSON into an ordered JsonNode tree by walking the
// bytes with a json.Decoder Token() stream. Trailing data after the top-level
// value is an error, matching JSON.parse. Never panics.
func ParseJson(raw string) (*JsonNode, error) {
	dec := json.NewDecoder(strings.NewReader(raw))
	dec.UseNumber() // keep the raw literal instead of a float64
	root, err := decodeNode(dec)
	if err != nil {
		return nil, err
	}
	// JSON.parse rejects anything after the top-level value.
	if _, err := dec.Token(); err == io.EOF {
		return root, nil
	} else if err != nil {
		return nil, err
	}
	return nil, fmt.Errorf("invalid JSON: unexpected data after top-level value")
}

// decodeNode reads the next token and decodes the full value that starts
// with it.
func decodeNode(dec *json.Decoder) (*JsonNode, error) {
	tok, err := dec.Token()
	if err != nil {
		return nil, err
	}
	return nodeFromToken(dec, tok)
}

// nodeFromToken turns a decoded token (and, for delimiters, the tokens that
// follow) into an ordered JsonNode.
func nodeFromToken(dec *json.Decoder, tok json.Token) (*JsonNode, error) {
	switch t := tok.(type) {
	case json.Delim:
		switch t {
		case '{':
			n := &JsonNode{Type: TypeObject}
			for dec.More() {
				keyTok, err := dec.Token()
				if err != nil {
					return nil, err
				}
				key, ok := keyTok.(string)
				if !ok {
					return nil, fmt.Errorf("json: unexpected non-string object key %v", keyTok)
				}
				val, err := decodeNode(dec)
				if err != nil {
					return nil, err
				}
				n.Members = append(n.Members, JsonMember{Key: key, Value: val})
			}
			if _, err := dec.Token(); err != nil { // consume '}'
				return nil, err
			}
			return n, nil
		case '[':
			n := &JsonNode{Type: TypeArray}
			for dec.More() {
				item, err := decodeNode(dec)
				if err != nil {
					return nil, err
				}
				n.Items = append(n.Items, item)
			}
			if _, err := dec.Token(); err != nil { // consume ']'
				return nil, err
			}
			return n, nil
		default:
			return nil, fmt.Errorf("json: unexpected delimiter %v", t)
		}
	case string:
		return &JsonNode{Type: TypeString, Str: t}, nil
	case json.Number:
		return &JsonNode{Type: TypeNumber, Num: t.String()}, nil
	case bool:
		return &JsonNode{Type: TypeBoolean, Bool: t}, nil
	case nil:
		return &JsonNode{Type: TypeNull}, nil
	default:
		return nil, fmt.Errorf("json: unexpected token %v", tok)
	}
}

// PreviewOf renders the source-ish preview of a primitive: 'null' for null,
// strings unquoted (truncated at 80 runes: 79 runes + the … ellipsis rune),
// numbers as their literal, booleans as true/false. Callers only pass
// primitives, mirroring the TS previewOf. Never panics (nil → ”).
func PreviewOf(n *JsonNode) string {
	if n == nil {
		return ""
	}
	switch n.Type {
	case TypeNull:
		return "null"
	case TypeString:
		runes := []rune(n.Str)
		if len(runes) > 80 {
			return string(runes[:79]) + "…"
		}
		return n.Str
	case TypeNumber:
		return n.Num
	case TypeBoolean:
		if n.Bool {
			return "true"
		}
		return "false"
	default: // object | array — branches carry no preview
		return ""
	}
}

// FlattenJson flattens an ordered JsonNode into preorder rows. The root row
// comes first with path '$', empty key, depth 0. Object children follow
// document order; array children follow index order — the TS insertion-order
// walk exactly. Never panics (nil → no rows).
func FlattenJson(root *JsonNode) []TreeRow {
	rows := []TreeRow{}
	var walk func(n *JsonNode, path, key string, depth int)
	walk = func(n *JsonNode, path, key string, depth int) {
		if n == nil {
			return
		}
		isBranch := n.Type == TypeObject || n.Type == TypeArray
		row := TreeRow{Path: path, Key: key, Depth: depth, Type: n.Type}
		if isBranch {
			if n.Type == TypeArray {
				row.ChildCount = intPtr(len(n.Items))
			} else {
				row.ChildCount = intPtr(len(n.Members))
			}
		} else {
			row.Preview = strPtr(PreviewOf(n))
		}
		rows = append(rows, row)
		if n.Type == TypeArray {
			for i, item := range n.Items {
				walk(item, path+"["+strconv.Itoa(i)+"]", strconv.Itoa(i), depth+1)
			}
		} else if n.Type == TypeObject {
			for _, m := range n.Members {
				walk(m.Value, path+"."+m.Key, m.Key, depth+1)
			}
		}
	}
	walk(root, "$", "", 0)
	return rows
}

// FilterResult carries the filtered rows plus the paths of rows whose OWN
// text matched (for highlight in the island). MatchCount counts rows kept,
// not text hits.
type FilterResult struct {
	Rows       []TreeRow
	Matches    map[string]bool
	MatchCount int
}

// FilterRows keeps rows whose key, path, or preview matches query as a
// case-insensitive substring, plus their ancestors so the tree stays
// navigable (parent = strip the last .key or [i] segment, whichever ends
// later). An empty (or whitespace-only) query returns all rows with an empty
// match set. Branch rows match when a descendant match keeps them alive.
func FilterRows(rows []TreeRow, query string) FilterResult {
	q := strings.ToLower(strings.TrimSpace(query))
	if q == "" {
		return FilterResult{Rows: rows, Matches: map[string]bool{}, MatchCount: len(rows)}
	}

	var own []TreeRow
	for _, r := range rows {
		prev := ""
		if r.Preview != nil {
			prev = *r.Preview
		}
		if strings.Contains(strings.ToLower(r.Key), q) ||
			strings.Contains(strings.ToLower(r.Path), q) ||
			strings.Contains(strings.ToLower(prev), q) {
			own = append(own, r)
		}
	}
	matches := make(map[string]bool, len(own))
	for _, r := range own {
		matches[r.Path] = true
	}
	// Keep ancestors of matches so the structure survives filtering.
	keep := make(map[string]bool, len(own)*2)
	for _, r := range own {
		path := r.Path
		keep[path] = true
		for path != "$" {
			// Parent = strip the last .key or [i] segment, whichever ends later.
			cut := strings.LastIndex(path, ".")
			if br := strings.LastIndex(path, "["); br > cut {
				cut = br
			}
			path = path[:cut]
			keep[path] = true
		}
	}
	kept := make([]TreeRow, 0, len(keep))
	for _, r := range rows {
		if keep[r.Path] {
			kept = append(kept, r)
		}
	}
	return FilterResult{Rows: kept, Matches: matches, MatchCount: len(kept)}
}

// Counts tallies rows per type, for the island's summary chips.
type Counts struct {
	Object  int
	Array   int
	String  int
	Number  int
	Boolean int
	Null    int
}

// TypeCounts counts rows per type. It mirrors the TS Record<JsonNodeType,
// number> with every key initialized to 0.
func TypeCounts(rows []TreeRow) Counts {
	var c Counts
	for _, r := range rows {
		switch r.Type {
		case TypeObject:
			c.Object++
		case TypeArray:
			c.Array++
		case TypeString:
			c.String++
		case TypeNumber:
			c.Number++
		case TypeBoolean:
			c.Boolean++
		case TypeNull:
			c.Null++
		}
	}
	return c
}

// ParseToTreeResult is the parse + flatten + count outcome in one step for
// the island entry point. On empty input: no rows, nil Counts, nil Err (the
// island shows nothing). On invalid JSON: no rows, nil Counts, Err set.
type ParseToTreeResult struct {
	Rows   []TreeRow
	Counts *Counts
	Err    error
}

// ParseToTree parses raw, flattens and counts in one step. Empty input (after
// trimming) is not an error. The Err message surfaces the parser's message.
func ParseToTree(raw string) ParseToTreeResult {
	text := strings.TrimSpace(raw)
	if text == "" {
		return ParseToTreeResult{Rows: []TreeRow{}}
	}
	root, err := ParseJson(text)
	if err != nil {
		return ParseToTreeResult{Rows: []TreeRow{}, Err: err}
	}
	rows := FlattenJson(root)
	counts := TypeCounts(rows)
	return ParseToTreeResult{Rows: rows, Counts: &counts}
}

Also available in 1 other language

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