TOML ⇄ JSON Converter — Go source
Convert TOML to JSON and back. Tables, array-of-tables, and dotted keys round-trip; bare TOML dates stay date-only, datetimes become ISO-8601 strings. Swap carries the result into the input.
This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Package tomljsonconverter is the Go twin of CosmoDev's src/lib/toml-json.ts
// (dual source: the web lib wraps smol-toml in TypeScript, the CLI lib uses
// github.com/BurntSushi/toml + encoding/json in Go — kept in lock-step). Pure +
// deterministic, never panics. The table-driven tests in
// toml-json-converter_test.go share vectors with src/lib/toml-json.test.ts so
// the two implementations are held to the same contract.
//
// Parity notes (verified byte-for-byte against smol-toml):
// - TOML → pretty JSON (2-space, json.Encoder SetIndent/SetEscapeHTML(false)),
// document key order preserved via the decoder's MetaData.Keys() (map
// iteration would scramble it). The Encoder's trailing newline is trimmed
// so output matches the TS JSON.stringify(...) bytes exactly.
// - Bare TOML dates stay date-only strings ("2024-01-15"); datetimes become
// ISO-8601 with milliseconds: offset datetimes keep their authored offset
// ("2024-01-15T10:30:00.000Z" / "...+02:00"), local datetimes serialize
// without a zone ("2024-01-15T10:30:00.000"), local times as
// "10:30:00.500" — mirroring smol-toml's TomlDate.toISOString().
// - Non-finite floats (inf/nan) serialize as JSON null, exactly like
// JSON.stringify(Infinity).
// - JSON → TOML mirrors smol-toml's stringify layout: scalars before
// sub-tables, "[sub]" table headers, "[[items]]" array-of-tables blocks,
// inline "{ a = 1, b = 2 }" tables and "[ 1, 2, 3 ]" arrays, empty
// intermediate tables elided ("[a.b]" instead of "[a]" + "[a.b]"), null
// values skipped, top-level non-objects rejected.
package tomljsonconverter
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/BurntSushi/toml"
)
// ConvertResult mirrors the TS ConvertResult union. Error is "" (zero value)
// when there was no error, standing in for the TS `error: null` case.
type ConvertResult struct {
Output string
Error string
}
// maxDepth bounds recursion, mirroring smol-toml stringify's maxDepth: 1000
// default (JS would overflow its call stack around the same order of depth).
const maxDepth = 1000
// TomlToJson parses a TOML document and pretty-prints it as JSON (2-space
// indent, no HTML escaping). It is the Go twin of tomlToJson() in
// src/lib/toml-json.ts and must agree with it on every shared vector.
// Empty/whitespace input yields empty output with no error; broken TOML
// returns the parser's error message.
func TomlToJson(raw string) ConvertResult {
text := strings.TrimSpace(raw)
if text == "" {
return ConvertResult{Output: "", Error: ""}
}
// Decode into a plain map; document order is recovered separately from
// MetaData.Keys() (Go maps have no order, and encoding/json sorts keys).
var doc map[string]any
md, err := toml.NewDecoder(strings.NewReader(text)).Decode(&doc)
if err != nil {
return ConvertResult{Output: "", Error: err.Error()}
}
compact, err := buildOrderedJSON(doc, md)
if err != nil {
return ConvertResult{Output: "", Error: err.Error()}
}
// Re-indent the compact JSON through encoding/json so the formatting is
// exactly what json.Encoder with SetIndent("", " ") produces.
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetIndent("", " ")
enc.SetEscapeHTML(false)
if err := enc.Encode(json.RawMessage(compact)); err != nil {
return ConvertResult{Output: "", Error: err.Error()}
}
// json.Encoder always appends '\n'; the TS twin (JSON.stringify) does not.
return ConvertResult{Output: strings.TrimSuffix(buf.String(), "\n"), Error: ""}
}
// ---------------------------------------------------------------------------
// TOML → JSON: ordered emission
// ---------------------------------------------------------------------------
// tomlNode is one node of the ordered skeleton built from MetaData.Keys().
// Leaf nodes carry the decoded value resolved from the doc tree; Hash nodes
// list child keys in document order; ArrayHash nodes list one child skeleton
// per array-of-tables element, in document order.
type tomlNode struct {
keys []string
children map[string]*tomlNode
isHash bool
isArray bool
elements []*tomlNode
isLeaf bool
value any
}
// ensureChild returns the child skeleton for key, creating it (appending to
// the ordered key list) if needed. Descending into an array-of-tables node
// lands in its most recently added element, because MetaData.Keys() always
// lists an ArrayHash header immediately before that element's own keys.
func (n *tomlNode) ensureChild(key string) *tomlNode {
if n.isArray {
if len(n.elements) > 0 {
n = n.elements[len(n.elements)-1]
} else {
return n
}
}
if n.children == nil {
n.children = make(map[string]*tomlNode)
}
child, ok := n.children[key]
if !ok {
child = &tomlNode{}
n.children[key] = child
n.keys = append(n.keys, key)
}
return child
}
// buildOrderedJSON walks MetaData.Keys() in document order to build the
// ordered skeleton (resolving each key's decoded value as it goes), then
// emits compact JSON in that same order.
func buildOrderedJSON(doc map[string]any, md toml.MetaData) ([]byte, error) {
root := &tomlNode{}
// inlineOrder records, per parent path, the position (index of first
// appearance) at which each sub-key occurs in the document. Paths cannot
// address array elements, so the sub-keys of the inline tables inside one
// plain array share a single position index — used to emit those maps
// deterministically. The map keeps key insertion O(1) (no linear scan).
inlineOrder := make(map[string]map[string]int)
pathKey := func(k toml.Key) string { return strings.Join(k, "\x00") }
for _, k := range md.Keys() {
parent, container := walk(root, doc, k[:len(k)-1])
leaf := parent.ensureChild(k[len(k)-1])
switch md.Type(k...) {
case "ArrayHash":
leaf.isArray = true
leaf.elements = append(leaf.elements, &tomlNode{})
case "Hash":
leaf.isHash = true
default: // Integer, Float, String, Bool, Datetime, Array (incl. inline tables)
leaf.isLeaf = true
leaf.value = resolveValue(container, k[len(k)-1])
}
if len(k) >= 2 {
pk := pathKey(k[:len(k)-1])
last := k[len(k)-1]
pos := inlineOrder[pk]
if pos == nil {
pos = make(map[string]int)
inlineOrder[pk] = pos
}
if _, seen := pos[last]; !seen {
pos[last] = len(pos) // index of first appearance
}
}
}
var buf bytes.Buffer
writeSkeleton(&buf, root, nil, inlineOrder)
return buf.Bytes(), nil
}
// walk descends the skeleton along path (creating plain Hash nodes as needed —
// dotted keys never get a Hash entry of their own), resolving values from the
// doc tree: entering an array-of-tables container selects its last element
// (Keys() lists that element's ArrayHash header immediately before its keys).
// It returns the skeleton node at path and the decoded value at path.
func walk(root *tomlNode, doc map[string]any, path []string) (*tomlNode, any) {
node := root
val := any(doc)
for _, seg := range path {
switch v := val.(type) {
case []map[string]any:
if len(v) > 0 {
val = v[len(v)-1]
} else {
val = nil
}
case []any:
if len(v) > 0 {
val = v[len(v)-1]
} else {
val = nil
}
}
if m, ok := val.(map[string]any); ok {
val = m[seg]
} else {
val = nil
}
node = node.ensureChild(seg)
}
return node, val
}
// resolveValue reads the value for the final segment of a key from its parent
// container (a table map, or the last element of an array-of-tables).
func resolveValue(container any, last string) any {
switch c := container.(type) {
case map[string]any:
return c[last]
case []map[string]any:
if len(c) > 0 {
return c[len(c)-1][last]
}
case []any:
if len(c) > 0 {
if m, ok := c[len(c)-1].(map[string]any); ok {
return m[last]
}
}
}
return nil
}
// writeSkeleton emits compact JSON for the skeleton tree in document order.
// path is the current key path (used to look up inline-table key order).
func writeSkeleton(buf *bytes.Buffer, node *tomlNode, path []string, inlineOrder map[string]map[string]int) {
if node.isArray {
buf.WriteByte('[')
for i, elem := range node.elements {
if i > 0 {
buf.WriteByte(',')
}
// Array elements extend the array's own path (Keys() lists
// element keys as [array..., leaf]).
writeSkeleton(buf, elem, path, inlineOrder)
}
buf.WriteByte(']')
return
}
buf.WriteByte('{')
for i, key := range node.keys {
if i > 0 {
buf.WriteByte(',')
}
buf.Write(appendJSONString(nil, key))
buf.WriteByte(':')
child := node.children[key]
if child.isLeaf {
writeJSONValue(buf, child.value, strings.Join(append(path, key), "\x00"), inlineOrder)
} else {
writeSkeleton(buf, child, append(path, key), inlineOrder)
}
}
buf.WriteByte('}')
}
// writeJSONValue appends the compact JSON form of a decoded TOML value
// (scalar, []any plain array, or map[string]any inline table). pathKey is the
// "\x00"-joined path of the value, used to recover inline-table key order.
func writeJSONValue(buf *bytes.Buffer, v any, pathKey string, inlineOrder map[string]map[string]int) {
switch x := v.(type) {
case nil:
buf.WriteString("null")
case bool:
if x {
buf.WriteString("true")
} else {
buf.WriteString("false")
}
case int64:
buf.WriteString(strconv.FormatInt(x, 10))
case float64:
buf.WriteString(jsonFloat(x))
case string:
buf.Write(appendJSONString(nil, x))
case time.Time:
buf.Write(appendJSONString(nil, tomlDatetimeJSON(x)))
case []any:
buf.WriteByte('[')
for i, elem := range x {
if i > 0 {
buf.WriteByte(',')
}
writeJSONValue(buf, elem, pathKey, inlineOrder)
}
buf.WriteByte(']')
case map[string]any:
// Inline table nested inside a plain array: MetaData.Keys() cannot
// address elements, so order keys by their first appearance under the
// array's path; never-seen keys sort alphabetically after.
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sortInlineKeys(keys, inlineOrder[pathKey])
buf.WriteByte('{')
for i, k := range keys {
if i > 0 {
buf.WriteByte(',')
}
buf.Write(appendJSONString(nil, k))
buf.WriteByte(':')
writeJSONValue(buf, x[k], pathKey, inlineOrder)
}
buf.WriteByte('}')
default:
buf.WriteString("null")
}
}
// sortInlineKeys orders inline-table keys by their recorded document position
// (order of first appearance), with unknown keys sorted alphabetically after.
// pos is the per-path position index built by buildOrderedJSON; a nil pos (or
// missing path) ranks every key unknown, i.e. purely alphabetical.
func sortInlineKeys(keys []string, pos map[string]int) {
unknown := len(pos)
sort.SliceStable(keys, func(i, j int) bool {
ra, aOK := pos[keys[i]]
rb, bOK := pos[keys[j]]
if !aOK {
ra = unknown
}
if !bOK {
rb = unknown
}
if ra != rb {
return ra < rb
}
if !aOK && !bOK {
return keys[i] < keys[j]
}
return false
})
}
// tomlDatetimeJSON renders a decoded TOML datetime exactly like
// smol-toml's TomlDate.toISOString() (used by JSON.stringify):
// - date-local → "2006-01-02"
// - time-local → "15:04:05.000"
// - datetime-local → "2006-01-02T15:04:05.000" (no zone)
// - offset datetime → authored wall time + authored zone
// ("...T10:30:00.000Z" / "...T10:30:00.000+02:00")
//
// The local flavors are formatted in the location the parser attached (the
// authored wall-clock fields), so output never depends on the machine TZ.
func tomlDatetimeJSON(t time.Time) string {
switch t.Location().String() {
case "date-local":
return t.Format("2006-01-02")
case "time-local":
return t.Format("15:04:05.000")
case "datetime-local":
return t.Format("2006-01-02T15:04:05.000")
default:
return t.Format("2006-01-02T15:04:05.000Z07:00")
}
}
// jsonFloat formats a float like encoding/json with SetEscapeHTML(false)
// (which is also byte-identical to JS JSON.stringify for finite numbers).
// Non-finite floats become null, matching JSON.stringify(Infinity) → "null".
func jsonFloat(f float64) string {
if math.IsNaN(f) || math.IsInf(f, 0) {
return "null"
}
abs := math.Abs(f)
format := byte('f')
if abs != 0 && (abs < 1e-6 || abs >= 1e21) {
format = 'e'
}
b := strconv.AppendFloat(nil, f, format, -1, 64)
if format == 'e' {
// Clean up exponent zero-padding, as encoding/json does: "1e-07" → "1e-7".
n := len(b)
if n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' {
b[n-2] = b[n-1]
b = b[:n-1]
}
}
return string(b)
}
// appendJSONString escapes s as a JSON string literal the way encoding/json
// with SetEscapeHTML(false) does (JS JSON.stringify-compatible: no HTML
// escaping; control chars and lone surrogates handled; U+2028/U+2029 escaped
// as encoding/json always does).
func appendJSONString(b []byte, s string) []byte {
b = append(b, '"')
for i := 0; i < len(s); {
c := s[i]
if c < utf8.RuneSelf {
switch c {
case '"':
b = append(b, '\\', '"')
case '\\':
b = append(b, '\\', '\\')
case '\b':
b = append(b, '\\', 'b')
case '\f':
b = append(b, '\\', 'f')
case '\n':
b = append(b, '\\', 'n')
case '\r':
b = append(b, '\\', 'r')
case '\t':
b = append(b, '\\', 't')
default:
if c < 0x20 {
b = append(b, '\\', 'u', '0', '0', "0123456789abcdef"[c>>4], "0123456789abcdef"[c&0xF])
} else {
b = append(b, c)
}
}
i++
continue
}
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
b = append(b, `�`...)
i++
continue
}
if r == 0x2028 || r == 0x2029 {
b = append(b, '\\', 'u', '2', '0', '2', byte('8'+r-0x2028))
i += size
continue
}
b = append(b, s[i:i+size]...)
i += size
}
return append(b, '"')
}
// ---------------------------------------------------------------------------
// JSON → TOML
// ---------------------------------------------------------------------------
// JsonToToml parses a JSON document and serializes it as TOML, mirroring
// smol-toml's stringify(): nested objects become "[sub]" tables, arrays of
// objects become "[[items]]" blocks, other arrays and objects inside them are
// inline, null values are skipped, and key order follows the JSON text. It is
// the Go twin of jsonToToml() in src/lib/toml-json.ts and must agree with it
// on every shared vector.
func JsonToToml(raw string) ConvertResult {
text := strings.TrimSpace(raw)
if text == "" {
return ConvertResult{Output: "", Error: ""}
}
root, err := parseOrderedJSON(text)
if err != nil {
return ConvertResult{Output: "", Error: err.Error()}
}
out, err := stringifyTOML(root)
if err != nil {
return ConvertResult{Output: "", Error: err.Error()}
}
return ConvertResult{Output: out, Error: ""}
}
// jval is an ordered JSON value (key order = textual order, duplicate keys
// keep first position and last value, exactly like JSON.parse).
type jval struct {
kind byte // 'o' object, 'a' array, 's' string, 'n' number, 'b' bool, 'z' null
keys []string
vals map[string]*jval
arr []*jval
str string
num json.Number
bool bool
}
// parseOrderedJSON decodes JSON preserving object key order via the
// encoding/json token stream.
func parseOrderedJSON(text string) (*jval, error) {
dec := json.NewDecoder(strings.NewReader(text))
dec.UseNumber()
v, err := decodeValue(dec, 0)
if err != nil {
return nil, err
}
// Reject trailing data, as JSON.parse does.
if dec.More() {
return nil, errors.New("unexpected trailing data after JSON value")
}
return v, nil
}
func decodeValue(dec *json.Decoder, depth int) (*jval, error) {
if depth > maxDepth {
return nil, errors.New("maximum object depth exceeded")
}
tok, err := dec.Token()
if err != nil {
return nil, err
}
switch t := tok.(type) {
case json.Delim:
switch t {
case '{':
v := &jval{kind: 'o', vals: make(map[string]*jval)}
for dec.More() {
keyTok, err := dec.Token()
if err != nil {
return nil, err
}
key, ok := keyTok.(string)
if !ok {
return nil, errors.New("invalid object key")
}
child, err := decodeValue(dec, depth+1)
if err != nil {
return nil, err
}
if _, exists := v.vals[key]; !exists {
v.keys = append(v.keys, key)
}
v.vals[key] = child
}
if _, err := dec.Token(); err != nil { // consume '}'
return nil, err
}
return v, nil
case '[':
v := &jval{kind: 'a'}
for dec.More() {
child, err := decodeValue(dec, depth+1)
if err != nil {
return nil, err
}
v.arr = append(v.arr, child)
}
if _, err := dec.Token(); err != nil { // consume ']'
return nil, err
}
return v, nil
default:
return nil, fmt.Errorf("unexpected delimiter %c", rune(t))
}
case string:
return &jval{kind: 's', str: t}, nil
case json.Number:
return &jval{kind: 'n', num: t}, nil
case bool:
return &jval{kind: 'b', bool: t}, nil
case nil:
return &jval{kind: 'z'}, nil
default:
return nil, fmt.Errorf("unexpected token %v", tok)
}
}
// stringifyTOML is a direct port of smol-toml's stringify(stringifyTable(...))
// layout algorithm. A single strings.Builder is threaded through the whole
// emission (table headers, blocks and inline values all append into it), so no
// step copies an accumulated string.
func stringifyTOML(root *jval) (string, error) {
// JS: stringify(null) throws while reading a Date method off null.
if root.kind == 'z' {
return "", errors.New(`cannot read properties of null (reading 'getUTCDate')`)
}
if root.kind != 'o' {
return "", errors.New("stringify can only be called with an object")
}
var b strings.Builder
if err := stringifyTable("", root, "", 0, &b); err != nil {
return "", err
}
str := b.String()
if str == "" || str[len(str)-1] != '\n' {
return str + "\n", nil
}
return str, nil
}
// stringifyTable ports stringifyTable(tableKey, obj, prefix, depth).
// tableKey "" means "root/element content" (JS passes 0, falsy) — no header.
// Everything is appended into the shared Builder b.
func stringifyTable(tableKey string, obj *jval, prefix string, depth int, b *strings.Builder) error {
if depth > maxDepth {
return errors.New("could not stringify the object: maximum object depth exceeded")
}
// Classify each key structurally first: scalar lines ("key = value")
// versus "[sub]"/"[[arr]]" blocks. smol-toml emits all scalar lines before
// any blocks, and creates the table header only if there is content under
// it (or nothing at all below — bare "[e]" for empty tables). The shared
// Builder cannot rewind, so the split must be known before emitting.
var hasPreamble, hasTables bool
for _, k := range obj.keys {
v := obj.vals[k]
if v == nil || v.kind == 'z' {
continue // smol-toml silently skips null/undefined values
}
if v.kind == 'o' || (v.kind == 'a' && isArrayOfTables(v)) {
hasTables = true
} else {
hasPreamble = true
}
}
if tableKey != "" && (hasPreamble || !hasTables) {
if hasPreamble {
b.WriteString("[" + tableKey + "]\n")
} else {
b.WriteString("[" + tableKey + "]")
}
}
// Emit scalar lines, then blocks (the original preamble-then-tables
// concatenation order): a "\n" precedes every block, and the first block
// is additionally separated from the scalar lines above it (the original
// joined preamble and tables with "\n" only when both were non-empty —
// every successfully emitted block is non-empty, so blocks > 0 is exact).
blocks := 0
for _, k := range obj.keys {
v := obj.vals[k]
if v == nil || v.kind == 'z' {
continue // smol-toml silently skips null/undefined values
}
key := formatTOMLKey(k)
if v.kind == 'a' && isArrayOfTables(v) {
if blocks > 0 || hasPreamble {
b.WriteByte('\n')
}
blocks++
if err := stringifyArrayTable(v, joinKey(prefix, key), depth+1, b); err != nil {
return err
}
} else if v.kind == 'o' {
if blocks > 0 || hasPreamble {
b.WriteByte('\n')
}
blocks++
tblKey := joinKey(prefix, key)
if err := stringifyTable(tblKey, v, tblKey, depth+1, b); err != nil {
return err
}
} else {
b.WriteString(key)
b.WriteString(" = ")
if err := stringifyTOMLValue(v, depth, b); err != nil {
return err
}
b.WriteByte('\n')
}
}
return nil
}
// stringifyArrayTable ports stringifyArrayTable(array, key, depth). Each
// "[[key]]" element body is emitted into the shared Builder b.
func stringifyArrayTable(array *jval, key string, depth int, b *strings.Builder) error {
if depth > maxDepth {
return errors.New("could not stringify the object: maximum object depth exceeded")
}
for i, elem := range array.arr {
if i > 0 {
b.WriteByte('\n')
}
b.WriteString("[[" + key + "]]\n")
if err := stringifyTable("", elem, key, depth+1, b); err != nil {
return err
}
}
return nil
}
// isArrayOfTables mirrors smol-toml: a NON-EMPTY array whose elements are all
// objects (arrays and nulls disqualify — those serialize inline).
func isArrayOfTables(v *jval) bool {
if len(v.arr) == 0 {
return false
}
for _, elem := range v.arr {
if elem.kind != 'o' {
return false
}
}
return true
}
// joinKey joins a table prefix and key with '.', like the TS `${prefix}.${key}`.
func joinKey(prefix, key string) string {
if prefix == "" {
return key
}
return prefix + "." + key
}
// stringifyTOMLValue ports stringifyValue for scalar/inline values, appending
// the serialized form into the shared Builder b.
func stringifyTOMLValue(v *jval, depth int, b *strings.Builder) error {
if depth > maxDepth {
return errors.New("could not stringify the object: maximum object depth exceeded")
}
switch v.kind {
case 'n':
b.WriteString(jsNumber(v.num))
return nil
case 's':
b.WriteString(formatTOMLString(v.str))
return nil
case 'b':
if v.bool {
b.WriteString("true")
} else {
b.WriteString("false")
}
return nil
case 'a':
if len(v.arr) == 0 {
b.WriteString("[]")
return nil
}
b.WriteString("[ ")
for i, elem := range v.arr {
if elem == nil || elem.kind == 'z' {
return errors.New("arrays cannot contain null or undefined values")
}
if i > 0 {
b.WriteString(", ")
}
if err := stringifyTOMLValue(elem, depth+1, b); err != nil {
return err
}
}
b.WriteString(" ]")
return nil
case 'o':
if len(v.keys) == 0 {
b.WriteString("{}")
return nil
}
b.WriteString("{ ")
for i, k := range v.keys {
elem := v.vals[k]
// JS: stringifyValue(null) dispatches to stringifyInlineTable,
// whose Object.keys(null) throws TypeError.
if elem == nil || elem.kind == 'z' {
return errors.New("cannot convert undefined or null to object")
}
if i > 0 {
b.WriteString(", ")
}
b.WriteString(formatTOMLKey(k))
b.WriteString(" = ")
if err := stringifyTOMLValue(elem, depth+1, b); err != nil {
return err
}
}
b.WriteString(" }")
return nil
default:
return fmt.Errorf("cannot serialize value of kind %q", string(v.kind))
}
}
// isBareKey matches smol-toml's BARE_KEY = /^[a-z0-9-_]+$/i.
func isBareKey(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_') {
return false
}
}
return true
}
// formatTOMLKey emits a bare key when possible, a quoted string otherwise.
func formatTOMLKey(s string) string {
if isBareKey(s) {
return s
}
return formatTOMLString(s)
}
// formatTOMLString mirrors smol-toml's formatString: JSON.stringify-compatible
// escaping plus DEL (U+007F) escaped as "\u007f", invalid UTF-8 coerced to
// U+FFFD (s.toWellFormed()).
func formatTOMLString(s string) string {
escaped := string(appendJSONString(nil, strings.ToValidUTF8(s, "�")))
return strings.ReplaceAll(escaped, "\x7f", `\u007f`)
}
// maxSafeInteger is JS Number.MAX_SAFE_INTEGER (2^53-1).
const maxSafeInteger = 9007199254740991.0
// jsNumber formats a JSON number the way smol-toml's stringifyValue would for
// a JS double: integers within the safe range print bare, unsafe integers get
// ".0" appended (toFixed(1)), and non-integers print JS's shortest form.
// Numbers are always parsed through float64, so precision matches JS exactly.
func jsNumber(n json.Number) string {
f, _ := strconv.ParseFloat(string(n), 64) // ErrRange → ±Inf, like JS Number("1e999") === Infinity
if math.IsNaN(f) {
return "nan"
}
if math.IsInf(f, 1) {
return "inf"
}
if math.IsInf(f, -1) {
return "-inf"
}
if f == 0 {
return "0" // String(-0) === "0"
}
if f == math.Trunc(f) {
if math.Abs(f) <= maxSafeInteger {
return strconv.FormatFloat(f, 'f', -1, 64)
}
// Unsafe integer: JS falls through to val.toFixed(1).
return strconv.FormatFloat(f, 'f', 1, 64)
}
abs := math.Abs(f)
if abs < 1e-6 || abs >= 1e21 {
s := strconv.FormatFloat(f, 'e', -1, 64)
// JS prints "1e-7", Go "1e-07": strip the leading exponent zero.
if i := strings.Index(s, "e-0"); i >= 0 {
s = s[:i+2] + s[i+3:]
}
return s
}
return strconv.FormatFloat(f, 'f', -1, 64)
}
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 →