chore: import upstream snapshot with attribution
@@ -0,0 +1,145 @@
|
||||
import type { DefaultTheme } from 'vitepress'
|
||||
import UnoCSS from 'unocss/vite'
|
||||
import { defineConfig } from 'vitepress'
|
||||
import llmstxt, { copyOrDownloadAsMarkdownButtons } from 'vitepress-plugin-llms'
|
||||
import { description, github, name, ogImage, ogUrl, releases, twitterImage, version } from './meta'
|
||||
|
||||
export default defineConfig({
|
||||
title: name,
|
||||
description,
|
||||
head: [
|
||||
['link', { rel: 'icon', href: '/favicon.svg', type: 'image/svg+xml' }],
|
||||
['meta', { name: 'author', content: 'Johann Schopplich' }],
|
||||
['meta', { property: 'og:type', content: 'website' }],
|
||||
['meta', { property: 'og:url', content: ogUrl }],
|
||||
['meta', { property: 'og:title', content: name }],
|
||||
['meta', { property: 'og:description', content: description }],
|
||||
['meta', { property: 'og:image', content: ogImage }],
|
||||
['meta', { name: 'twitter:title', content: name }],
|
||||
['meta', { name: 'twitter:description', content: description }],
|
||||
['meta', { name: 'twitter:image', content: twitterImage }],
|
||||
['meta', { name: 'twitter:site', content: '@jschopplich' }],
|
||||
['meta', { name: 'twitter:creator', content: '@jschopplich' }],
|
||||
['meta', { name: 'twitter:card', content: 'summary_large_image' }],
|
||||
],
|
||||
|
||||
vite: {
|
||||
// @ts-expect-error – UnoCSS types are not compatible with Vite yet
|
||||
plugins: [UnoCSS(), llmstxt()],
|
||||
},
|
||||
|
||||
themeConfig: {
|
||||
logo: '/favicon.svg',
|
||||
|
||||
nav: [
|
||||
{
|
||||
text: 'Playground',
|
||||
link: '/playground',
|
||||
},
|
||||
{
|
||||
text: 'Guide',
|
||||
activeMatch: '^/guide/',
|
||||
items: [
|
||||
{ text: 'Getting Started', link: '/guide/getting-started' },
|
||||
{ text: 'Format Overview', link: '/guide/format-overview' },
|
||||
{ text: 'Using TOON with LLMs', link: '/guide/llm-prompts' },
|
||||
{ text: 'Benchmarks', link: '/guide/benchmarks' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'CLI',
|
||||
link: '/cli/',
|
||||
},
|
||||
{
|
||||
text: 'Reference',
|
||||
activeMatch: '^/reference/',
|
||||
items: [
|
||||
{ text: 'API', link: '/reference/api' },
|
||||
{ text: 'Syntax Cheatsheet', link: '/reference/syntax-cheatsheet' },
|
||||
{ text: 'Specification', link: '/reference/spec' },
|
||||
{ text: 'Efficiency Formalization', link: '/reference/efficiency-formalization' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Ecosystem',
|
||||
activeMatch: '^/ecosystem/',
|
||||
items: [
|
||||
{ text: 'Tools & Playgrounds', link: '/ecosystem/tools-and-playgrounds' },
|
||||
{ text: 'Implementations', link: '/ecosystem/implementations' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: `v${version}`,
|
||||
items: [
|
||||
{
|
||||
text: 'Release Notes',
|
||||
link: releases,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
sidebar: {
|
||||
'/guide/': sidebarPrimary(),
|
||||
'/cli/': sidebarPrimary(),
|
||||
'/reference/': sidebarPrimary(),
|
||||
'/ecosystem/': sidebarPrimary(),
|
||||
},
|
||||
|
||||
socialLinks: [
|
||||
{ icon: 'github', link: github },
|
||||
],
|
||||
|
||||
footer: {
|
||||
message: 'Released under the <a href="https://opensource.org/licenses/MIT" target="_blank">MIT License</a>.',
|
||||
copyright: 'Copyright © 2025-PRESENT <a href="https://johannschopplich.com" target="_blank">Johann Schopplich</a>',
|
||||
},
|
||||
|
||||
search: {
|
||||
provider: 'local',
|
||||
},
|
||||
},
|
||||
markdown: {
|
||||
config(md) {
|
||||
md.use(copyOrDownloadAsMarkdownButtons)
|
||||
},
|
||||
math: true,
|
||||
},
|
||||
})
|
||||
|
||||
function sidebarPrimary(): DefaultTheme.SidebarItem[] {
|
||||
return [
|
||||
{
|
||||
text: 'Guide',
|
||||
items: [
|
||||
{ text: 'Getting Started', link: '/guide/getting-started' },
|
||||
{ text: 'Format Overview', link: '/guide/format-overview' },
|
||||
{ text: 'Using TOON with LLMs', link: '/guide/llm-prompts' },
|
||||
{ text: 'Benchmarks', link: '/guide/benchmarks' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Tooling',
|
||||
items: [
|
||||
{ text: 'Playground', link: '/playground' },
|
||||
{ text: 'CLI Reference', link: '/cli/' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Ecosystem',
|
||||
items: [
|
||||
{ text: 'Tools & Playgrounds', link: '/ecosystem/tools-and-playgrounds' },
|
||||
{ text: 'Implementations', link: '/ecosystem/implementations' },
|
||||
],
|
||||
},
|
||||
{
|
||||
text: 'Reference',
|
||||
items: [
|
||||
{ text: 'API (TypeScript)', link: '/reference/api' },
|
||||
{ text: 'Syntax Cheatsheet', link: '/reference/syntax-cheatsheet' },
|
||||
{ text: 'Specification', link: '/reference/spec' },
|
||||
{ text: 'Efficiency Formalization', link: '/reference/efficiency-formalization' },
|
||||
],
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export { description, version } from '../../packages/toon/package.json'
|
||||
|
||||
/* VitePress head */
|
||||
export const name = 'TOON'
|
||||
export const ogUrl = 'https://toonformat.dev/'
|
||||
export const ogImage = `${ogUrl}og.png`
|
||||
export const twitterImage = `${ogUrl}twitter.png`
|
||||
|
||||
/* GitHub and social links */
|
||||
export const github = 'https://github.com/toon-format/toon'
|
||||
export const releases = 'https://github.com/toon-format/toon/releases'
|
||||
export const twitter = 'https://twitter.com/jschopplich'
|
||||
@@ -0,0 +1,764 @@
|
||||
<script setup lang="ts">
|
||||
import type { Delimiter, EncodeOptions } from '../../../../packages/toon/src'
|
||||
import { useClipboard, useDebounceFn } from '@vueuse/core'
|
||||
import { unzlibSync, zlibSync } from 'fflate'
|
||||
import { base64ToUint8Array, stringToUint8Array, uint8ArrayToBase64, uint8ArrayToString } from 'uint8array-extras'
|
||||
import { computed, onMounted, ref, shallowRef, watch } from 'vue'
|
||||
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
|
||||
import { DEFAULT_DELIMITER, encode } from '../../../../packages/toon/src'
|
||||
import VPInput from './VPInput.vue'
|
||||
|
||||
type InputFormat = 'json' | 'yaml'
|
||||
type JsonFormat = 'pretty-2' | 'pretty-4' | 'pretty-tab' | 'compact'
|
||||
|
||||
interface PlaygroundState extends Required<Pick<EncodeOptions, 'delimiter' | 'indent' | 'keyFolding' | 'flattenDepth'>> {
|
||||
input: string
|
||||
inputFormat: InputFormat
|
||||
jsonFormat: JsonFormat
|
||||
/** Pre-YAML share URLs stored input under `json`. Read-only fallback. */
|
||||
json?: string
|
||||
}
|
||||
|
||||
function parseInput(text: string, format: InputFormat): unknown {
|
||||
return format === 'yaml' ? parseYaml(text) : JSON.parse(text)
|
||||
}
|
||||
|
||||
function stringifyInputYaml(value: unknown): string {
|
||||
return stringifyYaml(value, { lineWidth: 0 })
|
||||
}
|
||||
|
||||
const PRESETS = {
|
||||
hikes: {
|
||||
context: {
|
||||
task: 'Our favorite hikes together',
|
||||
location: 'Boulder',
|
||||
season: 'spring_2025',
|
||||
},
|
||||
friends: ['ana', 'luis', 'sam'],
|
||||
hikes: [
|
||||
{ id: 1, name: 'Blue Lake Trail', distanceKm: 7.5, elevationGain: 320, companion: 'ana', wasSunny: true },
|
||||
{ id: 2, name: 'Ridge Overlook', distanceKm: 9.2, elevationGain: 540, companion: 'luis', wasSunny: false },
|
||||
{ id: 3, name: 'Wildflower Loop', distanceKm: 5.1, elevationGain: 180, companion: 'sam', wasSunny: true },
|
||||
],
|
||||
},
|
||||
orders: {
|
||||
orders: [
|
||||
{
|
||||
orderId: 'ORD-001',
|
||||
customer: { name: 'Alice Chen', email: 'alice@example.com' },
|
||||
items: [
|
||||
{ sku: 'WIDGET-A', quantity: 2, price: 29.99 },
|
||||
{ sku: 'GADGET-B', quantity: 1, price: 49.99 },
|
||||
],
|
||||
total: 109.97,
|
||||
status: 'shipped',
|
||||
},
|
||||
{
|
||||
orderId: 'ORD-002',
|
||||
customer: { name: 'Bob Smith', email: 'bob@example.com' },
|
||||
items: [
|
||||
{ sku: 'THING-C', quantity: 3, price: 15.00 },
|
||||
],
|
||||
total: 45.00,
|
||||
status: 'delivered',
|
||||
},
|
||||
],
|
||||
},
|
||||
metrics: {
|
||||
metrics: [
|
||||
{ date: '2025-01-01', views: 5200, clicks: 180, conversions: 24, revenue: 2890.50 },
|
||||
{ date: '2025-01-02', views: 6100, clicks: 220, conversions: 31, revenue: 3450.00 },
|
||||
{ date: '2025-01-03', views: 4800, clicks: 165, conversions: 19, revenue: 2100.25 },
|
||||
{ date: '2025-01-04', views: 5900, clicks: 205, conversions: 28, revenue: 3200.00 },
|
||||
],
|
||||
},
|
||||
events: {
|
||||
logs: [
|
||||
{ timestamp: '2025-01-15T10:23:45Z', level: 'info', endpoint: '/api/users', statusCode: 200, responseTime: 45 },
|
||||
{ timestamp: '2025-01-15T10:24:12Z', level: 'error', endpoint: '/api/orders', statusCode: 500, responseTime: 120, error: { message: 'Database timeout', retryable: true } },
|
||||
{ timestamp: '2025-01-15T10:25:03Z', level: 'info', endpoint: '/api/products', statusCode: 200, responseTime: 32 },
|
||||
{ timestamp: '2025-01-15T10:26:47Z', level: 'warn', endpoint: '/api/payment', statusCode: 429, responseTime: 5, error: { message: 'Rate limit exceeded', retryable: true } },
|
||||
],
|
||||
},
|
||||
} as const
|
||||
const DELIMITER_OPTIONS: { value: Delimiter, label: string }[] = [
|
||||
{ value: ',', label: 'Comma (,)' },
|
||||
{ value: '\t', label: 'Tab (\\t)' },
|
||||
{ value: '|', label: 'Pipe (|)' },
|
||||
]
|
||||
const JSON_FORMAT_OPTIONS: { value: JsonFormat, label: string, indent: string | number | undefined }[] = [
|
||||
{ value: 'pretty-2', label: 'Pretty (2 spaces)', indent: 2 },
|
||||
{ value: 'pretty-4', label: 'Pretty (4 spaces)', indent: 4 },
|
||||
{ value: 'pretty-tab', label: 'Pretty (tabs)', indent: '\t' },
|
||||
{ value: 'compact', label: 'Compact', indent: undefined },
|
||||
]
|
||||
const DEFAULT_JSON = JSON.stringify(PRESETS.hikes, undefined, 2)
|
||||
const SHARE_URL_LIMIT = 8 * 1024
|
||||
|
||||
// Input state
|
||||
const inputText = ref(DEFAULT_JSON)
|
||||
const inputFormat = ref<InputFormat>('json')
|
||||
const jsonFormat = ref<JsonFormat>('pretty-2')
|
||||
const currentFormatIndent = computed(() =>
|
||||
JSON_FORMAT_OPTIONS.find(opt => opt.value === jsonFormat.value)?.indent,
|
||||
)
|
||||
const formattedInput = computed(() => {
|
||||
try {
|
||||
const data = parseInput(inputText.value, inputFormat.value)
|
||||
return inputFormat.value === 'yaml' ? stringifyInputYaml(data) : formatJson(data)
|
||||
}
|
||||
catch {
|
||||
return inputText.value
|
||||
}
|
||||
})
|
||||
|
||||
// Encoder options
|
||||
const delimiter = ref<Delimiter>(DEFAULT_DELIMITER)
|
||||
const indent = ref(2)
|
||||
const keyFolding = ref<'off' | 'safe'>('safe')
|
||||
const flattenDepth = ref(2)
|
||||
|
||||
// Encoding output
|
||||
const encodingResult = computed(() => {
|
||||
try {
|
||||
const parsedInput = parseInput(inputText.value, inputFormat.value)
|
||||
return {
|
||||
output: encode(parsedInput, {
|
||||
indent: indent.value,
|
||||
delimiter: delimiter.value,
|
||||
keyFolding: keyFolding.value,
|
||||
flattenDepth: flattenDepth.value,
|
||||
}),
|
||||
error: undefined,
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
const fallback = inputFormat.value === 'yaml' ? 'Invalid YAML' : 'Invalid JSON'
|
||||
return {
|
||||
output: '',
|
||||
error: error instanceof Error ? error.message : fallback,
|
||||
}
|
||||
}
|
||||
})
|
||||
const toonOutput = computed(() => encodingResult.value.output)
|
||||
const error = computed(() => encodingResult.value.error)
|
||||
|
||||
// Token analysis
|
||||
const tokenizer = shallowRef<typeof import('gpt-tokenizer') | undefined>()
|
||||
const inputTokens = computed(() =>
|
||||
tokenizer.value?.encode(formattedInput.value).length,
|
||||
)
|
||||
const toonTokens = computed(() =>
|
||||
tokenizer.value && toonOutput.value ? tokenizer.value.encode(toonOutput.value).length : undefined,
|
||||
)
|
||||
const tokenSavings = computed(() => {
|
||||
if (!inputTokens.value || !toonTokens.value)
|
||||
return
|
||||
|
||||
const diff = inputTokens.value - toonTokens.value
|
||||
const percent = Math.abs((diff / inputTokens.value) * 100).toFixed(1)
|
||||
const sign = diff > 0 ? '−' : '+'
|
||||
|
||||
return { diff, percent, sign, isSavings: diff > 0 }
|
||||
})
|
||||
|
||||
// UI state
|
||||
const canShareState = ref(true)
|
||||
const hasCopiedUrl = ref(false)
|
||||
|
||||
const { copy, copied } = useClipboard({ source: toonOutput })
|
||||
const updateUrl = useDebounceFn(() => {
|
||||
const hash = encodeState()
|
||||
const baseUrl = `${window.location.origin}${window.location.pathname}${window.location.search}`
|
||||
const targetUrl = `${baseUrl}#${hash}`
|
||||
|
||||
if (targetUrl.length > SHARE_URL_LIMIT) {
|
||||
canShareState.value = false
|
||||
return
|
||||
}
|
||||
|
||||
canShareState.value = true
|
||||
window.history.replaceState(null, '', `#${hash}`)
|
||||
}, 300)
|
||||
|
||||
watch([inputText, delimiter, indent, keyFolding, flattenDepth, jsonFormat, inputFormat], () => {
|
||||
updateUrl()
|
||||
})
|
||||
|
||||
watch(jsonFormat, () => {
|
||||
if (inputFormat.value !== 'json')
|
||||
return
|
||||
try {
|
||||
inputText.value = formatJson(JSON.parse(inputText.value))
|
||||
}
|
||||
catch {}
|
||||
})
|
||||
|
||||
watch(inputFormat, (next, prev) => {
|
||||
if (prev === next)
|
||||
return
|
||||
try {
|
||||
const data = parseInput(inputText.value, prev)
|
||||
inputText.value = next === 'yaml' ? stringifyInputYaml(data) : formatJson(data)
|
||||
}
|
||||
catch {}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
loadTokenizer()
|
||||
|
||||
const hash = window.location.hash.slice(1)
|
||||
if (!hash)
|
||||
return
|
||||
|
||||
const state = decodeState(hash)
|
||||
if (state) {
|
||||
inputText.value = state.input ?? state.json
|
||||
delimiter.value = state.delimiter
|
||||
indent.value = state.indent
|
||||
keyFolding.value = state.keyFolding ?? 'safe'
|
||||
flattenDepth.value = state.flattenDepth ?? 2
|
||||
jsonFormat.value = state.jsonFormat ?? 'pretty-2'
|
||||
inputFormat.value = state.inputFormat ?? 'json'
|
||||
}
|
||||
})
|
||||
|
||||
function formatJson(value: unknown) {
|
||||
return JSON.stringify(value, undefined, currentFormatIndent.value)
|
||||
}
|
||||
|
||||
function encodeState() {
|
||||
const state: PlaygroundState = {
|
||||
input: inputText.value,
|
||||
inputFormat: inputFormat.value,
|
||||
delimiter: delimiter.value,
|
||||
indent: indent.value,
|
||||
keyFolding: keyFolding.value,
|
||||
flattenDepth: flattenDepth.value,
|
||||
jsonFormat: jsonFormat.value,
|
||||
}
|
||||
|
||||
const compressedData = zlibSync(stringToUint8Array(JSON.stringify(state)))
|
||||
return uint8ArrayToBase64(compressedData, { urlSafe: true })
|
||||
}
|
||||
|
||||
function decodeState(hash: string) {
|
||||
try {
|
||||
const bytes = base64ToUint8Array(hash)
|
||||
const decompressedData = unzlibSync(bytes)
|
||||
const decodedData = uint8ArrayToString(decompressedData)
|
||||
if (decodedData)
|
||||
return JSON.parse(decodedData) as PlaygroundState
|
||||
}
|
||||
catch {}
|
||||
}
|
||||
|
||||
function loadPreset(name: keyof typeof PRESETS) {
|
||||
const data = PRESETS[name]
|
||||
inputText.value = inputFormat.value === 'yaml' ? stringifyInputYaml(data) : formatJson(data)
|
||||
}
|
||||
|
||||
async function copyShareUrl() {
|
||||
if (!canShareState.value)
|
||||
return
|
||||
|
||||
await navigator.clipboard.writeText(window.location.href)
|
||||
hasCopiedUrl.value = true
|
||||
setTimeout(() => (hasCopiedUrl.value = false), 2000)
|
||||
}
|
||||
|
||||
async function loadTokenizer() {
|
||||
tokenizer.value ??= await import('gpt-tokenizer')
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="playground">
|
||||
<div class="playground-container">
|
||||
<!-- Header -->
|
||||
<header class="playground-header">
|
||||
<h1>Playground</h1>
|
||||
<p>Convert JSON or YAML to TOON in real time.</p>
|
||||
</header>
|
||||
|
||||
<!-- Options Bar -->
|
||||
<div class="options-bar">
|
||||
<VPInput id="inputFormat" label="Input format">
|
||||
<select id="inputFormat" v-model="inputFormat">
|
||||
<option value="json">
|
||||
JSON
|
||||
</option>
|
||||
<option value="yaml">
|
||||
YAML
|
||||
</option>
|
||||
</select>
|
||||
</VPInput>
|
||||
|
||||
<VPInput id="delimiter" label="Delimiter">
|
||||
<select id="delimiter" v-model="delimiter">
|
||||
<option v-for="opt in DELIMITER_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</option>
|
||||
</select>
|
||||
</VPInput>
|
||||
|
||||
<VPInput id="indent" label="Indent">
|
||||
<input
|
||||
id="indent"
|
||||
v-model.number="indent"
|
||||
type="number"
|
||||
min="0"
|
||||
max="8"
|
||||
>
|
||||
</VPInput>
|
||||
|
||||
<VPInput id="keyFolding" label="Key Folding">
|
||||
<select id="keyFolding" v-model="keyFolding">
|
||||
<option value="off">
|
||||
Off
|
||||
</option>
|
||||
<option value="safe">
|
||||
Safe
|
||||
</option>
|
||||
</select>
|
||||
</VPInput>
|
||||
|
||||
<VPInput id="flattenDepth" label="Flatten Depth">
|
||||
<input
|
||||
id="flattenDepth"
|
||||
v-model.number="flattenDepth"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
:disabled="keyFolding === 'off'"
|
||||
>
|
||||
</VPInput>
|
||||
|
||||
<VPInput id="preset" label="Preset">
|
||||
<select id="preset" @change="(e) => loadPreset((e.target as HTMLSelectElement).value as keyof typeof PRESETS)">
|
||||
<option value="" disabled selected>
|
||||
Load example…
|
||||
</option>
|
||||
<option value="hikes">
|
||||
Hikes (mixed structure)
|
||||
</option>
|
||||
<option value="orders">
|
||||
Orders (nested objects)
|
||||
</option>
|
||||
<option value="metrics">
|
||||
Metrics (tabular data)
|
||||
</option>
|
||||
<option value="events">
|
||||
Events (semi-uniform)
|
||||
</option>
|
||||
</select>
|
||||
</VPInput>
|
||||
|
||||
<VPInput v-if="inputFormat === 'json'" id="jsonFormat" label="JSON Baseline">
|
||||
<select id="jsonFormat" v-model="jsonFormat">
|
||||
<option v-for="opt in JSON_FORMAT_OPTIONS" :key="opt.value" :value="opt.value">
|
||||
{{ opt.label }}
|
||||
</option>
|
||||
</select>
|
||||
</VPInput>
|
||||
|
||||
<button
|
||||
class="share-button"
|
||||
:class="[hasCopiedUrl && 'copied']"
|
||||
:aria-label="
|
||||
!canShareState
|
||||
? 'State too large to share via URL'
|
||||
: hasCopiedUrl
|
||||
? 'Link copied!'
|
||||
: 'Copy shareable URL'
|
||||
"
|
||||
:title="!canShareState ? 'State too large to share via URL' : undefined"
|
||||
:disabled="!canShareState"
|
||||
:aria-disabled="!canShareState"
|
||||
@click="copyShareUrl"
|
||||
>
|
||||
<span class="vpi-link" :class="[hasCopiedUrl && 'check']" aria-hidden="true" />
|
||||
<template v-if="!canShareState">
|
||||
Too large to share
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ hasCopiedUrl ? 'Copied!' : 'Share' }}
|
||||
</template>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Editor Container -->
|
||||
<div class="editor-container">
|
||||
<!-- Input -->
|
||||
<div class="editor-pane">
|
||||
<div class="pane-header">
|
||||
<span class="pane-title">{{ inputFormat === 'yaml' ? 'YAML Input' : 'JSON Input' }}</span>
|
||||
<span class="pane-stats">
|
||||
<span class="stat-primary" title="Token count of the formatted input">{{ inputTokens ?? '…' }} tokens</span>
|
||||
<span class="stat-secondary">{{ formattedInput.length }} chars</span>
|
||||
</span>
|
||||
</div>
|
||||
<textarea
|
||||
id="input"
|
||||
v-model="inputText"
|
||||
class="editor-textarea"
|
||||
spellcheck="false"
|
||||
:aria-label="inputFormat === 'yaml' ? 'YAML input' : 'JSON input'"
|
||||
:aria-describedby="error ? 'parse-error' : undefined"
|
||||
:aria-invalid="!!error"
|
||||
:placeholder="inputFormat === 'yaml' ? 'Enter YAML here…' : 'Enter JSON here…'"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- TOON Output -->
|
||||
<div class="editor-pane">
|
||||
<div class="pane-header">
|
||||
<span class="pane-title">
|
||||
TOON Output
|
||||
<span v-if="tokenSavings" class="savings-badge" :class="[!tokenSavings.isSavings && 'increase']">
|
||||
{{ tokenSavings.sign }}{{ tokenSavings.percent }}%
|
||||
</span>
|
||||
</span>
|
||||
<span class="pane-stats">
|
||||
<span class="stat-primary">{{ toonTokens ?? '…' }} tokens</span>
|
||||
<span class="stat-secondary">{{ toonOutput.length }} chars</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="editor-output">
|
||||
<button
|
||||
v-if="!error"
|
||||
class="copy-button"
|
||||
:class="[copied && 'copied']"
|
||||
:aria-label="copied ? 'Copied to clipboard' : 'Copy to clipboard'"
|
||||
:aria-pressed="copied"
|
||||
@click="copy()"
|
||||
/>
|
||||
<pre v-if="!error"><code>{{ toonOutput }}</code></pre>
|
||||
<div v-else id="parse-error" role="alert" class="error-message">
|
||||
{{ error }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.playground {
|
||||
padding: 32px 24px 32px;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.playground {
|
||||
padding: 48px 32px 48px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 960px) {
|
||||
.playground {
|
||||
padding: 48px 32px 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.playground-container {
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.playground-header {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.playground-header h1 {
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.02em;
|
||||
line-height: 40px;
|
||||
color: var(--vp-c-text-1);
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.playground-header h1 {
|
||||
font-size: 32px;
|
||||
}
|
||||
}
|
||||
|
||||
.playground-header p {
|
||||
font-size: 16px;
|
||||
line-height: 28px;
|
||||
color: var(--vp-c-text-2);
|
||||
}
|
||||
|
||||
.options-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
background: var(--vp-c-bg-soft);
|
||||
border-radius: 8px;
|
||||
border: 1px solid var(--vp-c-divider);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.options-bar {
|
||||
gap: 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.vpi-link {
|
||||
--icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' viewBox='0 0 24 24'%3E%3Cpath d='M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71'/%3E%3Cpath d='M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'/%3E%3C/svg%3E");
|
||||
display: inline-block;
|
||||
width: 1em;
|
||||
height: 1em;
|
||||
-webkit-mask: var(--icon) no-repeat;
|
||||
mask: var(--icon) no-repeat;
|
||||
-webkit-mask-size: 100% 100%;
|
||||
mask-size: 100% 100%;
|
||||
background-color: currentColor;
|
||||
}
|
||||
|
||||
.vpi-link.check {
|
||||
--icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' stroke='currentColor' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' viewBox='0 0 24 24'%3E%3Cpath d='M20 6 9 17l-5-5'/%3E%3C/svg%3E");
|
||||
}
|
||||
|
||||
.share-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 0 12px;
|
||||
height: 32px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--vp-c-text-1);
|
||||
background: var(--vp-c-bg);
|
||||
border: 1px solid var(--vp-c-border);
|
||||
border-radius: 6px;
|
||||
transition: border-color 0.25s, color 0.25s;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.share-button:hover {
|
||||
border-color: var(--vp-c-brand-1);
|
||||
color: var(--vp-c-brand-1);
|
||||
}
|
||||
|
||||
.share-button:focus-visible {
|
||||
outline: 2px solid var(--vp-c-brand-1);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.share-button.copied {
|
||||
border-color: var(--vp-c-green-1);
|
||||
color: var(--vp-c-green-1);
|
||||
}
|
||||
|
||||
.share-button:disabled {
|
||||
color: var(--vp-c-text-3);
|
||||
border-color: var(--vp-c-divider);
|
||||
background: var(--vp-c-bg-soft);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.editor-container {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.editor-container {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.editor-pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 500px;
|
||||
border: 1px solid var(--vp-c-divider);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
background: var(--vp-c-bg-soft);
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.editor-pane {
|
||||
min-height: 400px;
|
||||
}
|
||||
}
|
||||
|
||||
.editor-pane:focus-within {
|
||||
border-color: var(--vp-c-brand-1);
|
||||
}
|
||||
|
||||
.pane-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
background: var(--vp-c-bg-alt);
|
||||
border-bottom: 1px solid var(--vp-c-divider);
|
||||
}
|
||||
|
||||
.pane-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--vp-c-text-2);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.pane-stats {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin-left: auto;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 400;
|
||||
color: var(--vp-c-text-2);
|
||||
text-transform: none;
|
||||
letter-spacing: normal;
|
||||
}
|
||||
|
||||
.stat-primary {
|
||||
font-weight: 600;
|
||||
color: var(--vp-c-text-1);
|
||||
}
|
||||
|
||||
.stat-secondary {
|
||||
color: var(--vp-c-text-3);
|
||||
}
|
||||
|
||||
.savings-badge {
|
||||
display: inline-flex;
|
||||
padding: 2px 6px;
|
||||
font-size: 0.625rem;
|
||||
font-weight: 600;
|
||||
color: var(--vp-c-green-1);
|
||||
background: var(--vp-c-green-soft);
|
||||
border-radius: 4px;
|
||||
text-transform: none;
|
||||
letter-spacing: normal;
|
||||
}
|
||||
|
||||
.savings-badge.increase {
|
||||
color: var(--vp-c-yellow-1);
|
||||
background: var(--vp-c-yellow-soft);
|
||||
}
|
||||
|
||||
.copy-button {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
z-index: 3;
|
||||
border: 1px solid var(--vp-code-copy-code-border-color);
|
||||
border-radius: 4px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
background-color: var(--vp-code-copy-code-bg);
|
||||
opacity: 0;
|
||||
cursor: pointer;
|
||||
background-image: var(--vp-icon-copy);
|
||||
background-position: 50%;
|
||||
background-size: 20px;
|
||||
background-repeat: no-repeat;
|
||||
transition: border-color 0.25s, background-color 0.25s, opacity 0.25s;
|
||||
}
|
||||
|
||||
.editor-output:hover .copy-button,
|
||||
.copy-button:focus {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.copy-button:hover:not(:disabled),
|
||||
.copy-button.copied {
|
||||
border-color: var(--vp-code-copy-code-hover-border-color);
|
||||
background-color: var(--vp-code-copy-code-hover-bg);
|
||||
}
|
||||
|
||||
.copy-button:focus-visible {
|
||||
outline: 2px solid var(--vp-c-brand-1);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.copy-button:disabled {
|
||||
opacity: 0.3;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.copy-button.copied,
|
||||
.copy-button:hover.copied {
|
||||
border-radius: 0 4px 4px 0;
|
||||
background-image: var(--vp-icon-copied);
|
||||
}
|
||||
|
||||
.copy-button.copied::before,
|
||||
.copy-button:hover.copied::before {
|
||||
position: relative;
|
||||
top: -1px;
|
||||
transform: translateX(calc(-100% - 1px));
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
border: 1px solid var(--vp-code-copy-code-hover-border-color);
|
||||
border-right: 0;
|
||||
border-radius: 4px 0 0 4px;
|
||||
padding: 0 10px;
|
||||
width: fit-content;
|
||||
height: 40px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--vp-code-copy-code-active-text);
|
||||
background-color: var(--vp-code-copy-code-hover-bg);
|
||||
white-space: nowrap;
|
||||
content: var(--vp-code-copy-copied-text-content);
|
||||
}
|
||||
|
||||
.copy-button[aria-pressed="true"] {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.editor-textarea,
|
||||
.editor-output {
|
||||
flex: 1;
|
||||
padding: 16px;
|
||||
font-family: var(--vp-font-family-mono);
|
||||
font-size: 0.875rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.editor-textarea {
|
||||
resize: none;
|
||||
color: var(--vp-c-text-1);
|
||||
background: var(--vp-c-bg);
|
||||
}
|
||||
|
||||
.editor-output {
|
||||
position: relative;
|
||||
overflow: auto;
|
||||
background: var(--vp-code-block-bg);
|
||||
}
|
||||
|
||||
.editor-output pre {
|
||||
margin: 0;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
color: var(--vp-c-danger-1);
|
||||
padding: 8px 12px;
|
||||
background: var(--vp-c-danger-soft);
|
||||
border-radius: 4px;
|
||||
font-size: 0.875rem;
|
||||
font-family: var(--vp-font-family-base);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,68 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
label: string
|
||||
id: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="VPInput">
|
||||
<label :for="id" class="label">{{ label }}</label>
|
||||
<div class="input-wrapper">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.VPInput {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.label {
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--vp-c-text-2);
|
||||
}
|
||||
|
||||
.input-wrapper :deep(select),
|
||||
.input-wrapper :deep(input) {
|
||||
padding: 0 10px;
|
||||
height: 32px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: var(--vp-c-text-1);
|
||||
background-color: var(--vp-c-bg);
|
||||
border: 1px solid var(--vp-c-border);
|
||||
border-radius: 6px;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
|
||||
.input-wrapper :deep(select):hover,
|
||||
.input-wrapper :deep(input):hover,
|
||||
.input-wrapper :deep(select):focus,
|
||||
.input-wrapper :deep(input):focus {
|
||||
border-color: var(--vp-c-brand-1);
|
||||
}
|
||||
|
||||
.input-wrapper :deep(select:disabled),
|
||||
.input-wrapper :deep(input:disabled) {
|
||||
color: var(--vp-c-text-3);
|
||||
background-color: var(--vp-c-bg-soft);
|
||||
border-color: var(--vp-c-divider);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.input-wrapper :deep(select:disabled):hover,
|
||||
.input-wrapper :deep(input:disabled):hover,
|
||||
.input-wrapper :deep(select:disabled):focus,
|
||||
.input-wrapper :deep(input:disabled):focus {
|
||||
border-color: var(--vp-c-divider);
|
||||
}
|
||||
|
||||
.input-wrapper :deep(input[type="number"]) {
|
||||
width: 70px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { Theme } from 'vitepress'
|
||||
import CopyOrDownloadAsMarkdownButtons from 'vitepress-plugin-llms/vitepress-components/CopyOrDownloadAsMarkdownButtons.vue'
|
||||
import DefaultTheme from 'vitepress/theme'
|
||||
import PlaygroundLayout from './components/PlaygroundLayout.vue'
|
||||
import VPInput from './components/VPInput.vue'
|
||||
|
||||
import './vars.css'
|
||||
import './overrides.css'
|
||||
import 'uno.css'
|
||||
|
||||
const config: Theme = {
|
||||
extends: DefaultTheme,
|
||||
enhanceApp({ app }) {
|
||||
app.config.globalProperties.$spec = {
|
||||
version: '3.3',
|
||||
}
|
||||
app.component('CopyOrDownloadAsMarkdownButtons', CopyOrDownloadAsMarkdownButtons)
|
||||
app.component('PlaygroundLayout', PlaygroundLayout)
|
||||
app.component('VPInput', VPInput)
|
||||
},
|
||||
}
|
||||
|
||||
export default config
|
||||
@@ -0,0 +1,34 @@
|
||||
.dark [img-light] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
html:not(.dark) [img-dark] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
details summary {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.vp-doc [class*="language-"] code {
|
||||
color: var(--vp-c-text-1)
|
||||
}
|
||||
|
||||
.VPHomeHero .image-src {
|
||||
max-width: 112px;
|
||||
max-height: 112px;
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
.VPHomeHero .image-src {
|
||||
max-width: 144px;
|
||||
max-height: 144px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width:960px) {
|
||||
.VPHomeHero .image-src {
|
||||
max-width: 176px;
|
||||
max-height: 176px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Colors Theme
|
||||
* -------------------------------------------------------------------------- */
|
||||
|
||||
:root {
|
||||
--vp-c-brand-1: #d97c06;
|
||||
--vp-c-brand-2: #C57105;
|
||||
--vp-c-brand-3: #B16505;
|
||||
--vp-nav-logo-height: 20px;
|
||||
}
|
||||
|
||||
/**
|
||||
* Component: Home
|
||||
* -------------------------------------------------------------------------- */
|
||||
|
||||
:root {
|
||||
--vp-home-hero-name-color: transparent;
|
||||
--vp-home-hero-name-background: -webkit-linear-gradient(
|
||||
120deg,
|
||||
#fde98a 15%,
|
||||
#d97c06
|
||||
);
|
||||
--vp-home-hero-image-background-image: linear-gradient(
|
||||
-45deg,
|
||||
#d97c0660 30%,
|
||||
#fde98a60
|
||||
);
|
||||
--vp-home-hero-image-filter: blur(30px);
|
||||
}
|
||||
|
||||
@media (min-width: 640px) {
|
||||
:root {
|
||||
--vp-home-hero-image-filter: blur(56px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 960px) {
|
||||
:root {
|
||||
--vp-home-hero-image-filter: blur(72px);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
---
|
||||
description: Convert JSON to TOON and back from the command line, with token statistics, streaming, and delimiter options.
|
||||
---
|
||||
|
||||
# Command Line Interface
|
||||
|
||||
The `@toon-format/cli` package converts JSON to TOON and TOON to JSON. Use it to measure token savings before integrating TOON into your application, or to pipe JSON through TOON in shell workflows alongside tools like `curl` and `jq`. The CLI supports stdin/stdout, token statistics, streaming for large datasets, and every encoding option in the library.
|
||||
|
||||
The CLI is built on the `@toon-format/toon` TypeScript implementation and follows the [latest specification](/reference/spec).
|
||||
|
||||
## Usage
|
||||
|
||||
### Without Installation
|
||||
|
||||
Use `npx` to run the CLI without installing:
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [Encode]
|
||||
npx @toon-format/cli input.json -o output.toon
|
||||
```
|
||||
|
||||
```bash [Decode]
|
||||
npx @toon-format/cli data.toon -o output.json
|
||||
```
|
||||
|
||||
```bash [Stdin]
|
||||
echo '{"name": "Ada"}' | npx @toon-format/cli
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Global Installation
|
||||
|
||||
Or install globally for repeated use:
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [npm]
|
||||
npm install -g @toon-format/cli
|
||||
```
|
||||
|
||||
```bash [pnpm]
|
||||
pnpm add -g @toon-format/cli
|
||||
```
|
||||
|
||||
```bash [yarn]
|
||||
yarn global add @toon-format/cli
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
After global installation, use the `toon` command:
|
||||
|
||||
```bash
|
||||
toon input.json -o output.toon
|
||||
```
|
||||
|
||||
## Basic Usage
|
||||
|
||||
### Auto-Detection
|
||||
|
||||
The CLI automatically detects the operation based on file extension:
|
||||
- `.json` files → encode (JSON to TOON)
|
||||
- `.toon` files → decode (TOON to JSON)
|
||||
|
||||
When reading from stdin, use `--encode` or `--decode` flags to specify the operation (defaults to encode).
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [Encode JSON to TOON]
|
||||
toon input.json -o output.toon
|
||||
```
|
||||
|
||||
```bash [Decode TOON to JSON]
|
||||
toon data.toon -o output.json
|
||||
```
|
||||
|
||||
```bash [Output to stdout]
|
||||
toon input.json
|
||||
```
|
||||
|
||||
```bash [Pipe from stdin]
|
||||
cat data.json | toon
|
||||
echo '{"name": "Ada"}' | toon
|
||||
```
|
||||
|
||||
```bash [Decode from stdin]
|
||||
cat data.toon | toon --decode
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
By convention, TOON files use the `.toon` extension and the provisional media type `text/toon` (see [spec §17](https://github.com/toon-format/spec/blob/main/SPEC.md#17-iana-considerations)).
|
||||
|
||||
### Standard Input
|
||||
|
||||
Omit the input argument or use `-` to read from stdin. This enables piping data directly from other commands:
|
||||
|
||||
```bash
|
||||
# No argument needed
|
||||
cat data.json | toon
|
||||
|
||||
# Explicit stdin with hyphen (equivalent)
|
||||
cat data.json | toon -
|
||||
|
||||
# Decode from stdin
|
||||
cat data.toon | toon --decode
|
||||
```
|
||||
|
||||
## Performance
|
||||
|
||||
### Streaming Output
|
||||
|
||||
Both encoding and decoding operations use streaming output, writing incrementally without building the full output string in memory. This makes the CLI efficient for large datasets without requiring additional configuration.
|
||||
|
||||
**JSON → TOON (Encode)**:
|
||||
|
||||
- Streams TOON lines to output.
|
||||
- No full TOON string in memory.
|
||||
|
||||
**TOON → JSON (Decode)**:
|
||||
|
||||
- Uses the same event-based streaming decoder as the `decodeStream` API in `@toon-format/toon`.
|
||||
- Streams JSON tokens to output.
|
||||
- No full JSON string in memory.
|
||||
- When `--expandPaths safe` is enabled, falls back to non-streaming decode internally to apply deep-merge expansion before writing JSON.
|
||||
|
||||
Process large files with minimal memory usage:
|
||||
|
||||
```bash
|
||||
# Encode large JSON file
|
||||
toon huge-dataset.json -o output.toon
|
||||
|
||||
# Decode large TOON file
|
||||
toon huge-dataset.toon -o output.json
|
||||
|
||||
# Process millions of records efficiently via stdin
|
||||
cat million-records.json | toon > output.toon
|
||||
cat million-records.toon | toon --decode > output.json
|
||||
```
|
||||
|
||||
Peak memory usage scales with data depth, not total size. This allows processing arbitrarily large files as long as individual nested structures fit in memory.
|
||||
|
||||
::: tip Token Statistics
|
||||
When using the `--stats` flag with encode, the CLI builds the full TOON string once to compute accurate token counts. For maximum memory efficiency on very large files, omit `--stats`.
|
||||
:::
|
||||
|
||||
## Options
|
||||
|
||||
| Option | Description |
|
||||
| ------ | ----------- |
|
||||
| `-o, --output <file>` | Output file path (prints to stdout if omitted) |
|
||||
| `-e, --encode` | Force encode mode (overrides auto-detection) |
|
||||
| `-d, --decode` | Force decode mode (overrides auto-detection) |
|
||||
| `--delimiter <char>` | Array delimiter: `,` (comma), tab character, `\|` (pipe). Pass tab as `$'\t'` in bash/zsh |
|
||||
| `--indent <number>` | Indentation size (default: `2`) |
|
||||
| `--stats` | Show token count estimates and savings (encode only) |
|
||||
| `--no-strict` | Skip decode validation (array counts, indentation, header delimiter); last-write-wins on duplicate keys |
|
||||
| `--keyFolding <mode>` | Key folding mode: `off`, `safe` (default: `off`) |
|
||||
| `--flattenDepth <number>` | Maximum segments to fold (default: `Infinity`) – requires `--keyFolding safe` |
|
||||
| `--expandPaths <mode>` | Path expansion mode: `off`, `safe` (default: `off`) |
|
||||
| `--verbose` | Show full stack traces and cause chains for errors (default: `false`) |
|
||||
|
||||
## Advanced Examples
|
||||
|
||||
### Token Statistics
|
||||
|
||||
Show token savings when encoding:
|
||||
|
||||
```bash
|
||||
toon data.json --stats -o output.toon
|
||||
```
|
||||
|
||||
This helps you estimate token cost savings before sending data to LLMs.
|
||||
|
||||
Example output:
|
||||
|
||||
```
|
||||
✔ Encoded data.json → output.toon
|
||||
|
||||
ℹ Token estimates: ~15,145 (JSON) → ~8,745 (TOON)
|
||||
✔ Saved ~6,400 tokens (-42.3%)
|
||||
```
|
||||
|
||||
### Alternative Delimiters
|
||||
|
||||
TOON supports three delimiters: comma (default), tab, and pipe. Alternative delimiters can save additional tokens depending on the data.
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [Tab-separated (bash/zsh)]
|
||||
toon data.json --delimiter $'\t' -o output.toon
|
||||
```
|
||||
|
||||
```bash [Pipe-separated]
|
||||
toon data.json --delimiter "|" -o output.toon
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The `--delimiter` value must be the actual delimiter character. In bash/zsh, use `$'\t'` to pass a real tab; literal `"\t"` is rejected as an invalid delimiter.
|
||||
|
||||
**Tab delimiter example:**
|
||||
|
||||
::: code-group
|
||||
|
||||
```yaml [Tab]
|
||||
items[2 ]{id name qty price}:
|
||||
A1 Widget 2 9.99
|
||||
B2 Gadget 1 14.5
|
||||
```
|
||||
|
||||
```yaml [Comma (default)]
|
||||
items[2]{id,name,qty,price}:
|
||||
A1,Widget,2,9.99
|
||||
B2,Gadget,1,14.5
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
::: tip
|
||||
Tab delimiters often tokenize more efficiently than commas and reduce the need for quote-escaping. Use `--delimiter $'\t'` (bash/zsh) for maximum token savings on large tabular data. See [Delimiter Strategies](/reference/api#delimiter-strategies) for full guidance.
|
||||
:::
|
||||
|
||||
### Lenient Decoding
|
||||
|
||||
Skip validation for faster, more forgiving decoding:
|
||||
|
||||
```bash
|
||||
toon data.toon --no-strict -o output.json
|
||||
```
|
||||
|
||||
With `--no-strict`, the decoder stops enforcing array count matches, indentation multiples, and header delimiter mismatches. Duplicate sibling keys no longer throw – the last value wins. Malformed array headers fall back to plain `key: value` lines instead of erroring.
|
||||
|
||||
### Decode Error Output
|
||||
|
||||
When a TOON document fails to parse, the CLI renders the offending line with a caret pointing at the first non-whitespace character. Tabs are shown as `→` so the caret column reflects what the decoder actually saw.
|
||||
|
||||
For an input file that uses a tab to indent the second line (rendered here with `→`):
|
||||
|
||||
```
|
||||
a:
|
||||
→b: 1
|
||||
```
|
||||
|
||||
The CLI prints:
|
||||
|
||||
```
|
||||
ERROR Failed to decode TOON at line 2: Tabs are not allowed in indentation in strict mode
|
||||
|
||||
2 | →b: 1
|
||||
^
|
||||
```
|
||||
|
||||
The exit code is `1` on any error. Stack traces are suppressed by default. Pass `--verbose` to include the full stack and the underlying cause chain – useful when filing a bug report or diagnosing an unexpected error path:
|
||||
|
||||
```bash
|
||||
cat broken.toon | toon --decode --verbose
|
||||
```
|
||||
|
||||
::: tip Programmatic Access
|
||||
Decode errors are thrown as `ToonDecodeError` instances by the library. The CLI's caret rendering is built on the structured `line` and `source` fields exposed on that class. See the [Error Handling](/reference/api#error-handling) section of the API reference if you want the same diagnostic detail in your own code.
|
||||
:::
|
||||
|
||||
### Stdin Workflows
|
||||
|
||||
The CLI integrates seamlessly with Unix pipes and other command-line tools:
|
||||
|
||||
```bash
|
||||
# Convert API response to TOON
|
||||
curl https://api.example.com/data | toon --stats
|
||||
|
||||
# Process large dataset
|
||||
cat large-dataset.json | toon --delimiter $'\t' > output.toon
|
||||
|
||||
# Chain with jq
|
||||
jq '.results' data.json | toon > filtered.toon
|
||||
```
|
||||
|
||||
### Key Folding
|
||||
|
||||
Collapse nested wrapper chains to reduce tokens (since spec v1.5):
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [Basic key folding]
|
||||
toon input.json --keyFolding safe -o output.toon
|
||||
```
|
||||
|
||||
```bash [Limit folding depth]
|
||||
toon input.json --keyFolding safe --flattenDepth 2 -o output.toon
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
**Example:**
|
||||
|
||||
For data like:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"metadata": {
|
||||
"items": ["a", "b"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With `--keyFolding safe`, output becomes:
|
||||
|
||||
```yaml
|
||||
data.metadata.items[2]: a,b
|
||||
```
|
||||
|
||||
Instead of:
|
||||
|
||||
```yaml
|
||||
data:
|
||||
metadata:
|
||||
items[2]: a,b
|
||||
```
|
||||
|
||||
### Path Expansion
|
||||
|
||||
Reconstruct nested structure from folded keys when decoding:
|
||||
|
||||
```bash
|
||||
toon data.toon --expandPaths safe -o output.json
|
||||
```
|
||||
|
||||
This pairs with `--keyFolding safe` for lossless round-trips.
|
||||
|
||||
### Round-Trip Workflow
|
||||
|
||||
```bash
|
||||
# Encode with folding
|
||||
toon input.json --keyFolding safe -o compressed.toon
|
||||
|
||||
# Decode with expansion (restores original structure)
|
||||
toon compressed.toon --expandPaths safe -o output.json
|
||||
|
||||
# Verify round-trip
|
||||
diff input.json output.json
|
||||
```
|
||||
|
||||
### Combined Options
|
||||
|
||||
Combine multiple options for maximum efficiency:
|
||||
|
||||
```bash
|
||||
# Key folding + tab delimiter + stats
|
||||
toon data.json --keyFolding safe --delimiter $'\t' --stats -o output.toon
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
description: Official and community TOON implementations across languages, plus contribution pointers.
|
||||
---
|
||||
|
||||
# Implementations
|
||||
|
||||
TOON has official and community implementations across multiple programming languages. All implementations are intended to conform to the same [Specification](https://github.com/toon-format/spec) to ensure compatibility and interoperability.
|
||||
|
||||
The code examples throughout this documentation site use the TypeScript implementation by default, but the format and concepts apply equally to all languages.
|
||||
|
||||
> [!NOTE]
|
||||
> When implementing TOON in other languages, please follow the [spec](https://github.com/toon-format/spec/blob/main/SPEC.md) to ensure compatibility across implementations. The [conformance tests](https://github.com/toon-format/spec/tree/main/tests) provide language-agnostic test fixtures that validate your implementation.
|
||||
|
||||
## Official Implementations
|
||||
|
||||
These implementations are actively being developed by dedicated teams. Contributions are welcome! Join the effort by opening issues, submitting PRs, or discussing implementation details in the respective repositories.
|
||||
|
||||
| Language | Repository | Status | Maintainer |
|
||||
|----------|------------|--------|------------|
|
||||
| **.NET** | [toon-dotnet](https://github.com/toon-format/toon-dotnet) | In Development | Official Team |
|
||||
| **Dart** | [toon-dart](https://github.com/toon-format/toon-dart) | In Development | Official Team |
|
||||
| **Go** | [toon-go](https://github.com/toon-format/toon-go) | In Development | Official Team |
|
||||
| **Java** | [toon-java](https://github.com/toon-format/toon-java) | ✅ Stable | Official Team |
|
||||
| **Julia** | [ToonFormat.jl](https://github.com/toon-format/ToonFormat.jl) | ✅ Stable | Official Team |
|
||||
| **Python** | [toon-python](https://github.com/toon-format/toon-python) | ✅ Stable | Official Team |
|
||||
| **Rust** | [toon-rust](https://github.com/toon-format/toon-rust) | ✅ Stable | Official Team |
|
||||
| **Swift** | [toon-swift](https://github.com/toon-format/toon-swift) | ✅ Stable | Official Team |
|
||||
| **TypeScript/JavaScript** | [toon](https://github.com/toon-format/toon/tree/main/packages/toon) | ✅ Stable | Official Team |
|
||||
|
||||
## Community Implementations
|
||||
|
||||
Community members have created implementations in additional languages:
|
||||
|
||||
| Language | Repository | Maintainer |
|
||||
|----------|------------|------------|
|
||||
| **Apex** | [ApexToon](https://github.com/Eacaw/ApexToon) | [@Eacaw](https://github.com/Eacaw) |
|
||||
| **C** | [TOONc](https://github.com/UsboKirishima/TOONc) | [@UsboKirishima](https://github.com/UsboKirishima) |
|
||||
| **C++** | [ctoon](https://github.com/mohammadraziei/ctoon) | [@mohammadraziei](https://github.com/mohammadraziei) |
|
||||
| **C#** | [ToonEncoder](https://github.com/Cysharp/ToonEncoder) | [@Cysharp](https://github.com/Cysharp/ToonEncoder) |
|
||||
| **Clojure** | [toon](https://github.com/vadelabs/toon) | [@vadelabs](https://github.com/vadelabs) |
|
||||
| **Crystal** | [toon-crystal](https://github.com/mamantoha/toon-crystal) | [@mamantoha](https://github.com/mamantoha) |
|
||||
| **Delphi** | [delphi-toon](https://github.com/ernestoalconada/delphi-toon) | [@ernestoalconada](https://github.com/ernestoalconada) |
|
||||
| **Elixir** | [toon_ex](https://github.com/kentaro/toon_ex) | [@kentaro](https://github.com/kentaro) |
|
||||
| **Gleam** | [toon_codec](https://github.com/axelbellec/toon_codec) | [@axelbellec](https://github.com/axelbellec) |
|
||||
| **Go** | [gotoon](https://github.com/alpkeskin/gotoon) | [@alpkeskin](https://github.com/alpkeskin) |
|
||||
| **Java** | [json-io](https://github.com/jdereg/json-io) | [@jdereg](https://github.com/jdereg) |
|
||||
| **Kotlin** | [ktoon](https://github.com/lukelast/ktoon)| [@lukelast](https://github.com/lukelast) |
|
||||
| **Laravel Framework** | [laravel-toon](https://github.com/mischasigtermans/laravel-toon) | [@mischasigtermans](https://github.com/mischasigtermans) |
|
||||
| **Lua/Neovim** | [toon.nvim](https://github.com/thalesgelinger/toon.nvim) | [@thalesgelinger](https://github.com/thalesgelinger) |
|
||||
| **Matlab** | [ctoon](https://github.com/mohammadraziei/ctoon) | [@mohammadraziei](https://github.com/mohammadraziei) |
|
||||
| **OCaml** | [ocaml-toon](https://github.com/davesnx/ocaml-toon) | [@davesnx](https://github.com/davesnx) |
|
||||
| **Perl** | [Data::TOON](https://github.com/ytnobody/p5-Data-TOON) | [@ytnobody](https://github.com/ytnobody) |
|
||||
| **PHP** | [toon-php](https://github.com/HelgeSverre/toon-php) | [@HelgeSverre](https://github.com/HelgeSverre) |
|
||||
| **Python** (C++ backend) | [ctoon](https://github.com/mohammadraziei/ctoon) | [@mohammadraziei](https://github.com/mohammadraziei) |
|
||||
| **Python** (Rust backend) | [toons](https://github.com/alesanfra/toons) | [@alesanfra](https://github.com/alesanfra) |
|
||||
| **R** | [toon](https://github.com/laresbernardo/toon) | [@laresbernardo](https://github.com/laresbernardo) |
|
||||
| **Ruby** | [toon-ruby](https://github.com/andrepcg/toon-ruby) | [@andrepcg](https://github.com/andrepcg) |
|
||||
| **Scala** | [toon4s](https://github.com/vim89/toon4s) | [@vim89](https://github.com/vim89) |
|
||||
| **Zig** | [toon-zig](https://github.com/LatentEvals/toon-zig) | [@montanaflynn](https://github.com/montanaflynn) |
|
||||
|
||||
## Contributing an Implementation
|
||||
|
||||
Building a TOON implementation for a new language? Great! Here are some steps to get started:
|
||||
|
||||
1. **Follow the spec**: Implement the [latest specification](https://github.com/toon-format/spec/blob/main/SPEC.md).
|
||||
2. **Add tests**: Run the [reference test suite](https://github.com/toon-format/spec/tree/main/tests).
|
||||
3. **Document usage**: Provide a clear README with installation and usage examples.
|
||||
4. **Share it**: Open a PR to add your implementation to the README at [github.com/toon-format/toon](https://github.com/toon-format/toon).
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
description: TOON playgrounds, CLI, editor support, and ecosystem tools.
|
||||
---
|
||||
|
||||
# Tools and Playgrounds
|
||||
|
||||
Experiment with TOON format interactively using these tools for token comparison, format conversion, and validation.
|
||||
|
||||
## Playgrounds
|
||||
|
||||
### Official Playground
|
||||
|
||||
The [TOON Playground](/playground) lets you convert JSON or YAML to TOON in real time, compare token counts, and share your experiments via URL.
|
||||
|
||||
### Community Playgrounds
|
||||
|
||||
- [Format Tokenization Playground](https://www.curiouslychase.com/playground/format-tokenization-exploration)
|
||||
- [TOON Tools](https://toontools.vercel.app/)
|
||||
|
||||
## CLI Tool
|
||||
|
||||
The official TOON CLI provides command-line conversion, token statistics, and all encoding/decoding features. See the [CLI reference](/cli/) for full documentation.
|
||||
|
||||
```bash
|
||||
npx @toon-format/cli input.json --stats -o output.toon
|
||||
```
|
||||
|
||||
## Editor Support
|
||||
|
||||
### VS Code
|
||||
|
||||
[TOON Language Support](https://marketplace.visualstudio.com/items?itemName=vishalraut.vscode-toon) – Syntax highlighting, validation, conversion, and token analysis.
|
||||
|
||||
Install from the [VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=vishalraut.vscode-toon) or via command line:
|
||||
|
||||
```bash
|
||||
code --install-extension vishalraut.vscode-toon
|
||||
```
|
||||
|
||||
### Tree-sitter Grammar
|
||||
|
||||
[tree-sitter-toon](https://github.com/3swordman/tree-sitter-toon) – Grammar for Tree-sitter-compatible editors (Neovim, Helix, Emacs, Zed).
|
||||
|
||||
### Neovim
|
||||
|
||||
[toon.nvim](https://github.com/thalesgelinger/toon.nvim) – Lua-based plugin for Neovim.
|
||||
|
||||
### Other Editors
|
||||
|
||||
Use YAML syntax highlighting as a close approximation. Most editors allow associating `.toon` files with YAML language mode.
|
||||
|
||||
## Databases
|
||||
|
||||
### ToonStore
|
||||
|
||||
[ToonStore](https://github.com/Kalama-Tech/toonstoredb) – Redis-compatible embedded database (Rust) that stores data in TOON format.
|
||||
|
||||
## ORMs
|
||||
|
||||
### TORM
|
||||
|
||||
[TORM](https://github.com/Kalama-Tech/torm) – ORM that works with the ToonStore database, with SDKs for Node.js, Python, Go, and PHP.
|
||||
|
||||
## Web APIs
|
||||
|
||||
If you're building web applications that work with TOON, you can use the TypeScript library in the browser:
|
||||
|
||||
```ts
|
||||
import { decode, encode } from '@toon-format/toon'
|
||||
|
||||
// Works in browsers, Node.js, Deno, and Bun
|
||||
const toon = encode(data)
|
||||
const data = decode(toon)
|
||||
```
|
||||
|
||||
See the [API Reference](/reference/api) for details.
|
||||
|
||||
## MCP
|
||||
|
||||
### Tooner
|
||||
|
||||
[Tooner](https://github.com/chaindead/tooner) – MCP proxy that converts JSON tool responses to TOON.
|
||||
@@ -0,0 +1,586 @@
|
||||
---
|
||||
description: Retrieval accuracy and token efficiency results for TOON across mixed-structure and flat-only tracks.
|
||||
---
|
||||
|
||||
# Benchmarks
|
||||
|
||||
The benchmarks on this page measure TOON's performance across two key dimensions:
|
||||
|
||||
- **Retrieval Accuracy**: How well LLMs understand and extract information from different input formats.
|
||||
- **Token Efficiency**: How many tokens each format requires to represent the same data.
|
||||
|
||||
Benchmarks are organized into two tracks to ensure fair comparisons:
|
||||
|
||||
- **Mixed-Structure Track**: Datasets with nested or semi-uniform structures (TOON vs JSON, YAML, XML). CSV excluded as it cannot properly represent these structures.
|
||||
- **Flat-Only Track**: Datasets with flat tabular structures where CSV is applicable (CSV vs TOON vs JSON, YAML, XML).
|
||||
|
||||
## Retrieval Accuracy
|
||||
|
||||
<!-- automd:file src="../../benchmarks/results/retrieval-accuracy.md" -->
|
||||
|
||||
Benchmarks test LLM comprehension across different input formats using 209 data retrieval questions on 4 models.
|
||||
|
||||
<details>
|
||||
<summary><strong>Show Dataset Catalog</strong></summary>
|
||||
|
||||
#### Dataset Catalog
|
||||
|
||||
| Dataset | Rows | Structure | CSV Support | Eligibility |
|
||||
| ------- | ---- | --------- | ----------- | ----------- |
|
||||
| Uniform employee records | 100 | uniform | ✓ | 100% |
|
||||
| E-commerce orders with nested structures | 50 | nested | ✗ | 33% |
|
||||
| Time-series analytics data | 60 | uniform | ✓ | 100% |
|
||||
| Top 100 GitHub repositories | 100 | uniform | ✓ | 100% |
|
||||
| Semi-uniform event logs | 75 | semi-uniform | ✗ | 50% |
|
||||
| Deeply nested configuration | 11 | deep | ✗ | 0% |
|
||||
| Valid complete dataset (control) | 20 | uniform | ✓ | 100% |
|
||||
| Array truncated: 3 rows removed from end | 17 | uniform | ✓ | 100% |
|
||||
| Extra rows added beyond declared length | 23 | uniform | ✓ | 100% |
|
||||
| Inconsistent field count (missing salary in row 10) | 20 | uniform | ✓ | 100% |
|
||||
| Missing required fields (no email in multiple rows) | 20 | uniform | ✓ | 100% |
|
||||
|
||||
**Structure classes:**
|
||||
- **uniform**: All objects have identical fields with primitive values
|
||||
- **semi-uniform**: Mix of uniform and non-uniform structures
|
||||
- **nested**: Objects with nested structures (nested objects or arrays)
|
||||
- **deep**: Highly nested with minimal tabular eligibility
|
||||
|
||||
**CSV Support:** ✓ (supported), ✗ (not supported – would require lossy flattening)
|
||||
|
||||
**Eligibility:** Percentage of arrays that qualify for TOON's tabular format (uniform objects with primitive values)
|
||||
|
||||
</details>
|
||||
|
||||
#### Efficiency Ranking (Accuracy per 1K Tokens)
|
||||
|
||||
Each format ranked by efficiency (accuracy percentage per 1,000 tokens):
|
||||
|
||||
```
|
||||
TOON ████████████████████ 27.7 acc%/1K tok │ 76.4% acc │ 2,759 tokens
|
||||
JSON compact █████████████████░░░ 23.7 acc%/1K tok │ 73.7% acc │ 3,104 tokens
|
||||
YAML ██████████████░░░░░░ 19.9 acc%/1K tok │ 74.5% acc │ 3,749 tokens
|
||||
JSON ████████████░░░░░░░░ 16.4 acc%/1K tok │ 75.0% acc │ 4,587 tokens
|
||||
XML ██████████░░░░░░░░░░ 13.8 acc%/1K tok │ 72.1% acc │ 5,221 tokens
|
||||
```
|
||||
|
||||
*Efficiency score = (Accuracy % ÷ Tokens) × 1,000. Higher is better.*
|
||||
|
||||
> [!TIP]
|
||||
> TOON achieves **76.4%** accuracy (vs JSON's 75.0%) while using **39.9% fewer tokens**.
|
||||
|
||||
**Note on CSV:** Excluded from ranking as it only supports 109 of 209 questions (flat tabular data only). While CSV is highly token-efficient for simple tabular data, it cannot represent nested structures that other formats handle.
|
||||
|
||||
#### Per-Model Accuracy
|
||||
|
||||
Accuracy across 4 LLMs on 209 data retrieval questions:
|
||||
|
||||
```
|
||||
claude-haiku-4-5-20251001
|
||||
→ TOON ████████████░░░░░░░░ 59.8% (125/209)
|
||||
JSON ███████████░░░░░░░░░ 57.4% (120/209)
|
||||
YAML ███████████░░░░░░░░░ 56.0% (117/209)
|
||||
XML ███████████░░░░░░░░░ 55.5% (116/209)
|
||||
JSON compact ███████████░░░░░░░░░ 55.0% (115/209)
|
||||
CSV ██████████░░░░░░░░░░ 50.5% (55/109)
|
||||
|
||||
gemini-3-flash-preview
|
||||
XML ████████████████████ 98.1% (205/209)
|
||||
JSON ███████████████████░ 97.1% (203/209)
|
||||
YAML ███████████████████░ 97.1% (203/209)
|
||||
→ TOON ███████████████████░ 96.7% (202/209)
|
||||
JSON compact ███████████████████░ 96.7% (202/209)
|
||||
CSV ███████████████████░ 96.3% (105/109)
|
||||
|
||||
gpt-5-nano
|
||||
→ TOON ██████████████████░░ 90.9% (190/209)
|
||||
JSON compact ██████████████████░░ 90.9% (190/209)
|
||||
JSON ██████████████████░░ 89.0% (186/209)
|
||||
CSV ██████████████████░░ 89.0% (97/109)
|
||||
YAML █████████████████░░░ 87.1% (182/209)
|
||||
XML ████████████████░░░░ 80.9% (169/209)
|
||||
|
||||
grok-4-1-fast-non-reasoning
|
||||
→ TOON ████████████░░░░░░░░ 58.4% (122/209)
|
||||
YAML ████████████░░░░░░░░ 57.9% (121/209)
|
||||
JSON ███████████░░░░░░░░░ 56.5% (118/209)
|
||||
XML ███████████░░░░░░░░░ 54.1% (113/209)
|
||||
JSON compact ██████████░░░░░░░░░░ 52.2% (109/209)
|
||||
CSV ██████████░░░░░░░░░░ 51.4% (56/109)
|
||||
```
|
||||
|
||||
> [!TIP]
|
||||
> TOON achieves **76.4% accuracy** (vs JSON's 75.0%) while using **39.9% fewer tokens** on these datasets.
|
||||
|
||||
<details>
|
||||
<summary><strong>Performance by dataset, model, and question type</strong></summary>
|
||||
|
||||
#### Performance by Question Type
|
||||
|
||||
| Question Type | TOON | JSON | YAML | JSON compact | XML | CSV |
|
||||
| ------------- | ---- | ---- | ---- | ---- | ---- | ---- |
|
||||
| Field Retrieval | 99.6% | 99.3% | 98.5% | 98.5% | 98.9% | 100.0% |
|
||||
| Aggregation | 61.9% | 61.9% | 59.9% | 58.3% | 54.4% | 50.9% |
|
||||
| Filtering | 56.8% | 53.1% | 56.3% | 55.2% | 51.6% | 50.9% |
|
||||
| Structure Awareness | 89.0% | 87.0% | 84.0% | 84.0% | 81.0% | 85.9% |
|
||||
| Structural Validation | 70.0% | 60.0% | 60.0% | 55.0% | 85.0% | 80.0% |
|
||||
|
||||
#### Performance by Dataset
|
||||
|
||||
##### Uniform employee records
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `csv` | 73.2% | 2,334 | 120/164 |
|
||||
| `toon` | 73.2% | 2,498 | 120/164 |
|
||||
| `json-compact` | 73.8% | 3,924 | 121/164 |
|
||||
| `yaml` | 73.8% | 4,959 | 121/164 |
|
||||
| `json-pretty` | 73.8% | 6,331 | 121/164 |
|
||||
| `xml` | 74.4% | 7,296 | 122/164 |
|
||||
|
||||
##### E-commerce orders with nested structures
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `toon` | 82.3% | 7,458 | 135/164 |
|
||||
| `json-compact` | 78.7% | 7,110 | 129/164 |
|
||||
| `yaml` | 79.9% | 8,755 | 131/164 |
|
||||
| `json-pretty` | 79.3% | 11,234 | 130/164 |
|
||||
| `xml` | 77.4% | 12,649 | 127/164 |
|
||||
|
||||
##### Time-series analytics data
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `csv` | 75.0% | 1,411 | 90/120 |
|
||||
| `toon` | 78.3% | 1,553 | 94/120 |
|
||||
| `json-compact` | 74.2% | 2,354 | 89/120 |
|
||||
| `yaml` | 75.8% | 2,954 | 91/120 |
|
||||
| `json-pretty` | 75.0% | 3,681 | 90/120 |
|
||||
| `xml` | 72.5% | 4,389 | 87/120 |
|
||||
|
||||
##### Top 100 GitHub repositories
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `csv` | 65.9% | 8,527 | 87/132 |
|
||||
| `toon` | 66.7% | 8,779 | 88/132 |
|
||||
| `yaml` | 65.2% | 13,141 | 86/132 |
|
||||
| `json-compact` | 59.8% | 11,464 | 79/132 |
|
||||
| `json-pretty` | 63.6% | 15,157 | 84/132 |
|
||||
| `xml` | 56.1% | 17,105 | 74/132 |
|
||||
|
||||
##### Semi-uniform event logs
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `json-compact` | 68.3% | 4,839 | 82/120 |
|
||||
| `toon` | 65.0% | 5,819 | 78/120 |
|
||||
| `json-pretty` | 69.2% | 6,817 | 83/120 |
|
||||
| `yaml` | 61.7% | 5,847 | 74/120 |
|
||||
| `xml` | 58.3% | 7,729 | 70/120 |
|
||||
|
||||
##### Deeply nested configuration
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `json-compact` | 90.5% | 568 | 105/116 |
|
||||
| `toon` | 94.8% | 655 | 110/116 |
|
||||
| `yaml` | 93.1% | 675 | 108/116 |
|
||||
| `json-pretty` | 92.2% | 924 | 107/116 |
|
||||
| `xml` | 91.4% | 1,013 | 106/116 |
|
||||
|
||||
##### Valid complete dataset (control)
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `toon` | 100.0% | 535 | 4/4 |
|
||||
| `json-compact` | 100.0% | 787 | 4/4 |
|
||||
| `yaml` | 100.0% | 992 | 4/4 |
|
||||
| `json-pretty` | 100.0% | 1,274 | 4/4 |
|
||||
| `xml` | 25.0% | 1,462 | 1/4 |
|
||||
| `csv` | 0.0% | 483 | 0/4 |
|
||||
|
||||
##### Array truncated: 3 rows removed from end
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `csv` | 100.0% | 413 | 4/4 |
|
||||
| `xml` | 100.0% | 1,243 | 4/4 |
|
||||
| `toon` | 0.0% | 462 | 0/4 |
|
||||
| `json-pretty` | 0.0% | 1,085 | 0/4 |
|
||||
| `yaml` | 0.0% | 843 | 0/4 |
|
||||
| `json-compact` | 0.0% | 670 | 0/4 |
|
||||
|
||||
##### Extra rows added beyond declared length
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `csv` | 100.0% | 550 | 4/4 |
|
||||
| `toon` | 75.0% | 605 | 3/4 |
|
||||
| `json-compact` | 75.0% | 901 | 3/4 |
|
||||
| `xml` | 100.0% | 1,678 | 4/4 |
|
||||
| `yaml` | 75.0% | 1,138 | 3/4 |
|
||||
| `json-pretty` | 50.0% | 1,460 | 2/4 |
|
||||
|
||||
##### Inconsistent field count (missing salary in row 10)
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `csv` | 100.0% | 480 | 4/4 |
|
||||
| `json-compact` | 100.0% | 782 | 4/4 |
|
||||
| `yaml` | 100.0% | 985 | 4/4 |
|
||||
| `toon` | 100.0% | 1,008 | 4/4 |
|
||||
| `json-pretty` | 100.0% | 1,266 | 4/4 |
|
||||
| `xml` | 100.0% | 1,453 | 4/4 |
|
||||
|
||||
##### Missing required fields (no email in multiple rows)
|
||||
|
||||
| Format | Accuracy | Tokens | Correct/Total |
|
||||
| ------ | -------- | ------ | ------------- |
|
||||
| `csv` | 100.0% | 340 | 4/4 |
|
||||
| `xml` | 100.0% | 1,409 | 4/4 |
|
||||
| `toon` | 75.0% | 974 | 3/4 |
|
||||
| `json-pretty` | 50.0% | 1,225 | 2/4 |
|
||||
| `yaml` | 25.0% | 951 | 1/4 |
|
||||
| `json-compact` | 0.0% | 750 | 0/4 |
|
||||
|
||||
#### Performance by Model
|
||||
|
||||
##### claude-haiku-4-5-20251001
|
||||
|
||||
| Format | Accuracy | Correct/Total |
|
||||
| ------ | -------- | ------------- |
|
||||
| `toon` | 59.8% | 125/209 |
|
||||
| `json-pretty` | 57.4% | 120/209 |
|
||||
| `yaml` | 56.0% | 117/209 |
|
||||
| `xml` | 55.5% | 116/209 |
|
||||
| `json-compact` | 55.0% | 115/209 |
|
||||
| `csv` | 50.5% | 55/109 |
|
||||
|
||||
##### gemini-3-flash-preview
|
||||
|
||||
| Format | Accuracy | Correct/Total |
|
||||
| ------ | -------- | ------------- |
|
||||
| `xml` | 98.1% | 205/209 |
|
||||
| `json-pretty` | 97.1% | 203/209 |
|
||||
| `yaml` | 97.1% | 203/209 |
|
||||
| `toon` | 96.7% | 202/209 |
|
||||
| `json-compact` | 96.7% | 202/209 |
|
||||
| `csv` | 96.3% | 105/109 |
|
||||
|
||||
##### gpt-5-nano
|
||||
|
||||
| Format | Accuracy | Correct/Total |
|
||||
| ------ | -------- | ------------- |
|
||||
| `toon` | 90.9% | 190/209 |
|
||||
| `json-compact` | 90.9% | 190/209 |
|
||||
| `json-pretty` | 89.0% | 186/209 |
|
||||
| `csv` | 89.0% | 97/109 |
|
||||
| `yaml` | 87.1% | 182/209 |
|
||||
| `xml` | 80.9% | 169/209 |
|
||||
|
||||
##### grok-4-1-fast-non-reasoning
|
||||
|
||||
| Format | Accuracy | Correct/Total |
|
||||
| ------ | -------- | ------------- |
|
||||
| `toon` | 58.4% | 122/209 |
|
||||
| `yaml` | 57.9% | 121/209 |
|
||||
| `json-pretty` | 56.5% | 118/209 |
|
||||
| `xml` | 54.1% | 113/209 |
|
||||
| `json-compact` | 52.2% | 109/209 |
|
||||
| `csv` | 51.4% | 56/109 |
|
||||
|
||||
</details>
|
||||
|
||||
#### What's Being Measured
|
||||
|
||||
This benchmark tests **LLM comprehension and data retrieval accuracy** across different input formats. Each LLM receives formatted data and must answer questions about it. This does **not** test the model's ability to generate TOON output – only to read and understand it.
|
||||
|
||||
#### Datasets Tested
|
||||
|
||||
Eleven datasets designed to test different structural patterns and validation capabilities:
|
||||
|
||||
**Primary datasets:**
|
||||
|
||||
1. **Tabular** (100 employee records): Uniform objects with identical fields – optimal for TOON's tabular format.
|
||||
2. **Nested** (50 e-commerce orders): Complex structures with nested customer objects and item arrays.
|
||||
3. **Analytics** (60 days of metrics): Time-series data with dates and numeric values.
|
||||
4. **GitHub** (100 repositories): Real-world data from top GitHub repos by stars.
|
||||
5. **Event Logs** (75 logs): Semi-uniform data with ~50% flat logs and ~50% with nested error objects.
|
||||
6. **Nested Config** (1 configuration): Deeply nested configuration with minimal tabular eligibility.
|
||||
|
||||
**Structural validation datasets:**
|
||||
|
||||
7. **Control**: Valid complete dataset (baseline for validation)
|
||||
8. **Truncated**: Array with 3 rows removed from end (tests `[N]` length detection)
|
||||
9. **Extra rows**: Array with 3 additional rows beyond declared length
|
||||
10. **Width mismatch**: Inconsistent field count (missing salary in row 10)
|
||||
11. **Missing fields**: Systematic field omissions (no email in multiple rows)
|
||||
|
||||
#### Question Types
|
||||
|
||||
209 questions are generated dynamically across five categories:
|
||||
|
||||
- **Field retrieval (33%)**: Direct value lookups or values that can be read straight off a record (including booleans and simple counts such as array lengths)
|
||||
- Example: "What is Alice's salary?" → `75000`
|
||||
- Example: "How many items are in order ORD-0042?" → `3`
|
||||
- Example: "What is the customer name for order ORD-0042?" → `John Doe`
|
||||
|
||||
- **Aggregation (30%)**: Dataset-level totals and averages plus single-condition filters (counts, sums, min/max comparisons)
|
||||
- Example: "How many employees work in Engineering?" → `17`
|
||||
- Example: "What is the total revenue across all orders?" → `45123.50`
|
||||
- Example: "How many employees have salary > 80000?" → `23`
|
||||
|
||||
- **Filtering (23%)**: Multi-condition queries requiring compound logic (AND constraints across fields)
|
||||
- Example: "How many employees in Sales have salary > 80000?" → `5`
|
||||
- Example: "How many active employees have more than 10 years of experience?" → `8`
|
||||
|
||||
- **Structure awareness (12%)**: Tests format-native structural affordances (TOON's `[N]` count and `{fields}`, CSV's header row)
|
||||
- Example: "How many employees are in the dataset?" → `100`
|
||||
- Example: "List the field names for employees" → `id, name, email, department, salary, yearsExperience, active`
|
||||
- Example: "What is the department of the last employee?" → `Sales`
|
||||
|
||||
- **Structural validation (2%)**: Tests ability to detect incomplete, truncated, or corrupted data using structural metadata
|
||||
- Example: "Is this data complete and valid?" → `YES` (control dataset) or `NO` (corrupted datasets)
|
||||
- Tests TOON's `[N]` length validation and `{fields}` consistency checking
|
||||
- Demonstrates CSV's lack of structural validation capabilities
|
||||
|
||||
#### Evaluation Process
|
||||
|
||||
1. **Format conversion**: Each dataset is converted to all 6 formats (TOON, JSON, YAML, JSON compact, XML, CSV).
|
||||
2. **Query LLM**: Each model receives formatted data + question in a prompt and extracts the answer.
|
||||
3. **Validate deterministically**: Answers are validated using type-aware comparison (e.g., `50000` = `$50,000`, `Engineering` = `engineering`, `2025-01-01` = `January 1, 2025`) without requiring an LLM judge.
|
||||
|
||||
#### Models & Configuration
|
||||
|
||||
- **Models tested**: `claude-haiku-4-5-20251001`, `gemini-3-flash-preview`, `gpt-5-nano`, `grok-4-1-fast-non-reasoning`
|
||||
- **Token counting**: Using `gpt-tokenizer` with `o200k_base` encoding (GPT-5 tokenizer)
|
||||
- **Temperature**: Not set (models use their defaults)
|
||||
- **Total evaluations**: 209 questions × 6 formats × 4 models = 5,016 LLM calls
|
||||
|
||||
<!-- /automd -->
|
||||
|
||||
## Token Efficiency
|
||||
|
||||
Token counts are measured using the GPT-5 `o200k_base` tokenizer via [`gpt-tokenizer`](https://github.com/niieani/gpt-tokenizer). Savings are calculated against formatted JSON (2-space indentation) as the primary baseline, with additional comparisons to compact JSON (minified), YAML, and XML. Actual savings vary by model and tokenizer.
|
||||
|
||||
The benchmarks test datasets across different structural patterns (uniform, semi-uniform, nested, deeply nested) to show where TOON excels and where other formats may be better.
|
||||
|
||||
<!-- automd:file src="../../benchmarks/results/token-efficiency.md" -->
|
||||
|
||||
#### Mixed-Structure Track
|
||||
|
||||
Datasets with nested or semi-uniform structures. CSV excluded as it cannot properly represent these structures.
|
||||
|
||||
```
|
||||
🛒 E-commerce orders with nested structures ┊ Tabular: 33%
|
||||
│
|
||||
TOON █████████████░░░░░░░ 73,126 tokens
|
||||
├─ vs JSON (−33.3%) 109,599 tokens
|
||||
├─ vs JSON compact (+5.3%) 69,459 tokens
|
||||
├─ vs YAML (−14.4%) 85,415 tokens
|
||||
└─ vs XML (−40.7%) 123,344 tokens
|
||||
|
||||
🧾 Semi-uniform event logs ┊ Tabular: 50%
|
||||
│
|
||||
TOON █████████████████░░░ 154,084 tokens
|
||||
├─ vs JSON (−15.0%) 181,201 tokens
|
||||
├─ vs JSON compact (+19.9%) 128,529 tokens
|
||||
├─ vs YAML (−0.8%) 155,397 tokens
|
||||
└─ vs XML (−25.2%) 205,859 tokens
|
||||
|
||||
🧩 Deeply nested configuration ┊ Tabular: 0%
|
||||
│
|
||||
TOON ██████████████░░░░░░ 620 tokens
|
||||
├─ vs JSON (−31.9%) 911 tokens
|
||||
├─ vs JSON compact (+11.1%) 558 tokens
|
||||
├─ vs YAML (−6.3%) 662 tokens
|
||||
└─ vs XML (−38.2%) 1,003 tokens
|
||||
|
||||
──────────────────────────────────── Total ────────────────────────────────────
|
||||
TOON ████████████████░░░░ 227,830 tokens
|
||||
├─ vs JSON (−21.9%) 291,711 tokens
|
||||
├─ vs JSON compact (+14.7%) 198,546 tokens
|
||||
├─ vs YAML (−5.7%) 241,474 tokens
|
||||
└─ vs XML (−31.0%) 330,206 tokens
|
||||
```
|
||||
|
||||
#### Flat-Only Track
|
||||
|
||||
Datasets with flat tabular structures where CSV is applicable.
|
||||
|
||||
```
|
||||
👥 Uniform employee records ┊ Tabular: 100%
|
||||
│
|
||||
CSV ███████████████████░ 47,102 tokens
|
||||
TOON ████████████████████ 49,919 tokens (+6.0% vs CSV)
|
||||
├─ vs JSON (−60.7%) 127,063 tokens
|
||||
├─ vs JSON compact (−36.9%) 79,059 tokens
|
||||
├─ vs YAML (−50.1%) 100,011 tokens
|
||||
└─ vs XML (−65.9%) 146,579 tokens
|
||||
|
||||
📈 Time-series analytics data ┊ Tabular: 100%
|
||||
│
|
||||
CSV ██████████████████░░ 8,383 tokens
|
||||
TOON ████████████████████ 9,115 tokens (+8.7% vs CSV)
|
||||
├─ vs JSON (−59.0%) 22,245 tokens
|
||||
├─ vs JSON compact (−35.9%) 14,211 tokens
|
||||
├─ vs YAML (−49.0%) 17,858 tokens
|
||||
└─ vs XML (−65.8%) 26,616 tokens
|
||||
|
||||
⭐ Top 100 GitHub repositories ┊ Tabular: 100%
|
||||
│
|
||||
CSV ███████████████████░ 8,512 tokens
|
||||
TOON ████████████████████ 8,744 tokens (+2.7% vs CSV)
|
||||
├─ vs JSON (−42.3%) 15,144 tokens
|
||||
├─ vs JSON compact (−23.7%) 11,454 tokens
|
||||
├─ vs YAML (−33.4%) 13,128 tokens
|
||||
└─ vs XML (−48.9%) 17,095 tokens
|
||||
|
||||
──────────────────────────────────── Total ────────────────────────────────────
|
||||
CSV ███████████████████░ 63,997 tokens
|
||||
TOON ████████████████████ 67,778 tokens (+5.9% vs CSV)
|
||||
├─ vs JSON (−58.8%) 164,452 tokens
|
||||
├─ vs JSON compact (−35.3%) 104,724 tokens
|
||||
├─ vs YAML (−48.3%) 130,997 tokens
|
||||
└─ vs XML (−64.4%) 190,290 tokens
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><strong>Show detailed examples</strong></summary>
|
||||
|
||||
#### 📈 Time-series analytics data
|
||||
|
||||
**Savings:** 13,130 tokens (59.0% reduction vs JSON)
|
||||
|
||||
**JSON** (22,245 tokens):
|
||||
|
||||
```json
|
||||
{
|
||||
"metrics": [
|
||||
{
|
||||
"date": "2025-01-01",
|
||||
"views": 6138,
|
||||
"clicks": 174,
|
||||
"conversions": 12,
|
||||
"revenue": 2712.49,
|
||||
"bounceRate": 0.35
|
||||
},
|
||||
{
|
||||
"date": "2025-01-02",
|
||||
"views": 4616,
|
||||
"clicks": 274,
|
||||
"conversions": 34,
|
||||
"revenue": 9156.29,
|
||||
"bounceRate": 0.56
|
||||
},
|
||||
{
|
||||
"date": "2025-01-03",
|
||||
"views": 4460,
|
||||
"clicks": 143,
|
||||
"conversions": 8,
|
||||
"revenue": 1317.98,
|
||||
"bounceRate": 0.59
|
||||
},
|
||||
{
|
||||
"date": "2025-01-04",
|
||||
"views": 4740,
|
||||
"clicks": 125,
|
||||
"conversions": 13,
|
||||
"revenue": 2934.77,
|
||||
"bounceRate": 0.37
|
||||
},
|
||||
{
|
||||
"date": "2025-01-05",
|
||||
"views": 6428,
|
||||
"clicks": 369,
|
||||
"conversions": 19,
|
||||
"revenue": 1317.24,
|
||||
"bounceRate": 0.3
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**TOON** (9,115 tokens):
|
||||
|
||||
```
|
||||
metrics[5]{date,views,clicks,conversions,revenue,bounceRate}:
|
||||
2025-01-01,6138,174,12,2712.49,0.35
|
||||
2025-01-02,4616,274,34,9156.29,0.56
|
||||
2025-01-03,4460,143,8,1317.98,0.59
|
||||
2025-01-04,4740,125,13,2934.77,0.37
|
||||
2025-01-05,6428,369,19,1317.24,0.3
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### ⭐ Top 100 GitHub repositories
|
||||
|
||||
**Savings:** 6,400 tokens (42.3% reduction vs JSON)
|
||||
|
||||
**JSON** (15,144 tokens):
|
||||
|
||||
```json
|
||||
{
|
||||
"repositories": [
|
||||
{
|
||||
"id": 28457823,
|
||||
"name": "freeCodeCamp",
|
||||
"repo": "freeCodeCamp/freeCodeCamp",
|
||||
"description": "freeCodeCamp.org's open-source codebase and curriculum. Learn math, programming,…",
|
||||
"createdAt": "2014-12-24T17:49:19Z",
|
||||
"updatedAt": "2025-10-28T11:58:08Z",
|
||||
"pushedAt": "2025-10-28T10:17:16Z",
|
||||
"stars": 430886,
|
||||
"watchers": 8583,
|
||||
"forks": 42146,
|
||||
"defaultBranch": "main"
|
||||
},
|
||||
{
|
||||
"id": 132750724,
|
||||
"name": "build-your-own-x",
|
||||
"repo": "codecrafters-io/build-your-own-x",
|
||||
"description": "Master programming by recreating your favorite technologies from scratch.",
|
||||
"createdAt": "2018-05-09T12:03:18Z",
|
||||
"updatedAt": "2025-10-28T12:37:11Z",
|
||||
"pushedAt": "2025-10-10T18:45:01Z",
|
||||
"stars": 430877,
|
||||
"watchers": 6332,
|
||||
"forks": 40453,
|
||||
"defaultBranch": "master"
|
||||
},
|
||||
{
|
||||
"id": 21737465,
|
||||
"name": "awesome",
|
||||
"repo": "sindresorhus/awesome",
|
||||
"description": "😎 Awesome lists about all kinds of interesting topics",
|
||||
"createdAt": "2014-07-11T13:42:37Z",
|
||||
"updatedAt": "2025-10-28T12:40:21Z",
|
||||
"pushedAt": "2025-10-27T17:57:31Z",
|
||||
"stars": 410052,
|
||||
"watchers": 8017,
|
||||
"forks": 32029,
|
||||
"defaultBranch": "main"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**TOON** (8,744 tokens):
|
||||
|
||||
```
|
||||
repositories[3]{id,name,repo,description,createdAt,updatedAt,pushedAt,stars,watchers,forks,defaultBranch}:
|
||||
28457823,freeCodeCamp,freeCodeCamp/freeCodeCamp,"freeCodeCamp.org's open-source codebase and curriculum. Learn math, programming,…","2014-12-24T17:49:19Z","2025-10-28T11:58:08Z","2025-10-28T10:17:16Z",430886,8583,42146,main
|
||||
132750724,build-your-own-x,codecrafters-io/build-your-own-x,Master programming by recreating your favorite technologies from scratch.,"2018-05-09T12:03:18Z","2025-10-28T12:37:11Z","2025-10-10T18:45:01Z",430877,6332,40453,master
|
||||
21737465,awesome,sindresorhus/awesome,😎 Awesome lists about all kinds of interesting topics,"2014-07-11T13:42:37Z","2025-10-28T12:40:21Z","2025-10-27T17:57:31Z",410052,8017,32029,main
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<!-- /automd -->
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [Formal Byte-Level Model](/reference/efficiency-formalization) – Mathematical analysis of byte efficiency compared to JSON
|
||||
- [Specification](/reference/spec) – Formal TOON specification
|
||||
@@ -0,0 +1,365 @@
|
||||
---
|
||||
description: TOON syntax with concrete examples – objects, arrays, headers, key folding, and quoting rules.
|
||||
---
|
||||
|
||||
# Format Overview
|
||||
|
||||
TOON syntax reference with concrete examples. See [Getting Started](/guide/getting-started) for an introduction.
|
||||
|
||||
## Data Model
|
||||
|
||||
TOON models data the same way as JSON:
|
||||
|
||||
- **Primitives**: strings, numbers, booleans, and `null`
|
||||
- **Objects**: mappings from string keys to values
|
||||
- **Arrays**: ordered sequences of values
|
||||
|
||||
### Root Forms
|
||||
|
||||
A TOON document can represent different root forms:
|
||||
|
||||
- **Root object** (most common): Fields appear at depth 0 with no parent key
|
||||
- **Root array**: Begins with `[N]:` or `[N]{fields}:` at depth 0
|
||||
- **Root primitive**: A single primitive value (string, number, boolean, or null)
|
||||
|
||||
Most examples in these docs use root objects, but the format supports all three forms equally ([spec §5](https://github.com/toon-format/spec/blob/main/SPEC.md#5-concrete-syntax-and-root-form)).
|
||||
|
||||
## Objects
|
||||
|
||||
### Simple Objects
|
||||
|
||||
Objects with primitive values use `key: value` syntax, with one field per line:
|
||||
|
||||
```yaml
|
||||
id: 123
|
||||
name: Ada
|
||||
active: true
|
||||
```
|
||||
|
||||
Indentation replaces braces. One space follows the colon.
|
||||
|
||||
### Nested Objects
|
||||
|
||||
Nested objects add one indentation level (default: 2 spaces):
|
||||
|
||||
```yaml
|
||||
user:
|
||||
id: 123
|
||||
name: Ada
|
||||
```
|
||||
|
||||
When a key ends with `:` and has no value on the same line, it opens a nested object. All lines at the next indentation level belong to that object.
|
||||
|
||||
### Empty Objects
|
||||
|
||||
An empty object at the root yields an empty document (no lines). A nested empty object is `key:` alone, with no children.
|
||||
|
||||
## Arrays
|
||||
|
||||
TOON detects array structure and chooses the most efficient representation. Arrays always declare their length in brackets: `[N]`.
|
||||
|
||||
### Primitive Arrays (Inline)
|
||||
|
||||
Arrays of primitives (strings, numbers, booleans, null) are rendered inline:
|
||||
|
||||
```yaml
|
||||
tags[3]: admin,ops,dev
|
||||
```
|
||||
|
||||
The delimiter (comma by default) separates values. Strings containing the active delimiter must be quoted.
|
||||
|
||||
### Arrays of Objects (Tabular)
|
||||
|
||||
When all objects in an array share the same set of primitive-valued keys, TOON uses tabular format:
|
||||
|
||||
::: code-group
|
||||
|
||||
```yaml [Basic Tabular]
|
||||
items[2]{sku,qty,price}:
|
||||
A1,2,9.99
|
||||
B2,1,14.5
|
||||
```
|
||||
|
||||
```yaml [With Spaces in Values]
|
||||
users[2]{id,name,role}:
|
||||
1,Alice Admin,admin
|
||||
2,"Bob Smith",user
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The header `items[2]{sku,qty,price}:` declares:
|
||||
- **Array length**: `[2]` means 2 rows
|
||||
- **Field names**: `{sku,qty,price}` defines the columns
|
||||
- **Active delimiter**: comma (default)
|
||||
|
||||
Each row contains values in the same order as the field list. Values are encoded as primitives (strings, numbers, booleans, null) and separated by the delimiter.
|
||||
|
||||
> [!NOTE]
|
||||
> Tabular format requires identical field sets across all objects (same keys, order per object may vary), primitive values only (no nested arrays/objects), and at least one key per object – arrays that contain an empty `{}` element fall back to the expanded list form below.
|
||||
|
||||
### Mixed and Non-Uniform Arrays
|
||||
|
||||
Arrays that don't meet the tabular requirements use list format with hyphen markers:
|
||||
|
||||
```yaml
|
||||
items[3]:
|
||||
- 1
|
||||
- a: 1
|
||||
- text
|
||||
```
|
||||
|
||||
Each element starts with `- ` at one indentation level deeper than the parent array header.
|
||||
|
||||
### Objects as List Items
|
||||
|
||||
When an array element is an object, it appears as a list item:
|
||||
|
||||
```yaml
|
||||
items[2]:
|
||||
- id: 1
|
||||
name: First
|
||||
- id: 2
|
||||
name: Second
|
||||
extra: true
|
||||
```
|
||||
|
||||
When a tabular array is the first field of a list-item object, the tabular header appears on the hyphen line, with rows indented two levels deeper and other fields indented one level deeper:
|
||||
|
||||
```yaml
|
||||
items[1]:
|
||||
- users[2]{id,name}:
|
||||
1,Ada
|
||||
2,Bob
|
||||
status: active
|
||||
```
|
||||
|
||||
When the object has only a single tabular field, the same pattern applies:
|
||||
|
||||
```yaml
|
||||
items[1]:
|
||||
- users[2]{id,name}:
|
||||
1,Ada
|
||||
2,Bob
|
||||
```
|
||||
|
||||
This is the canonical encoding for list-item objects whose first field is a tabular array.
|
||||
|
||||
### Arrays of Arrays
|
||||
|
||||
When you have arrays containing primitive inner arrays:
|
||||
|
||||
```yaml
|
||||
pairs[2]:
|
||||
- [2]: 1,2
|
||||
- [2]: 3,4
|
||||
```
|
||||
|
||||
Each inner array gets its own header on the list-item line.
|
||||
|
||||
When the inner arrays are themselves arrays of objects or non-uniform arrays, the same `- [N]:` header appears on the hyphen line and the nested items follow one indent deeper:
|
||||
|
||||
```yaml
|
||||
items[3]:
|
||||
- summary
|
||||
- id: 1
|
||||
name: Ada
|
||||
- [2]:
|
||||
- id: 2
|
||||
- status: draft
|
||||
```
|
||||
|
||||
### Empty Arrays
|
||||
|
||||
Empty arrays render as `key: []` for fields and `[]` at the root:
|
||||
|
||||
```yaml
|
||||
items: []
|
||||
```
|
||||
|
||||
The legacy `items[0]:` form is still decoded for backward compatibility.
|
||||
|
||||
## Array Headers
|
||||
|
||||
### Header Syntax
|
||||
|
||||
Array headers follow this pattern:
|
||||
|
||||
```
|
||||
key[N<delimiter?>]<{fields}>:
|
||||
```
|
||||
|
||||
Where:
|
||||
- **N** is the non-negative integer length
|
||||
- **delimiter** (optional) explicitly declares the active delimiter:
|
||||
- Absent → comma (`,`)
|
||||
- `\t` (tab character) → tab delimiter
|
||||
- `|` → pipe delimiter
|
||||
- **fields** (optional) for tabular arrays: `{field1,field2,field3}`
|
||||
|
||||
> [!NOTE]
|
||||
> The array length `[N]` helps LLMs validate structure. If you ask a model to generate TOON output, explicit lengths let you detect truncation or malformed data.
|
||||
|
||||
### Delimiter Options
|
||||
|
||||
TOON supports three delimiters: comma (default), tab, and pipe. The delimiter is scoped to the array header that declares it.
|
||||
|
||||
::: code-group
|
||||
|
||||
```yaml [Comma (default)]
|
||||
items[2]{sku,name,qty,price}:
|
||||
A1,Widget,2,9.99
|
||||
B2,Gadget,1,14.5
|
||||
```
|
||||
|
||||
```yaml [Tab]
|
||||
items[2 ]{sku name qty price}:
|
||||
A1 Widget 2 9.99
|
||||
B2 Gadget 1 14.5
|
||||
```
|
||||
|
||||
```yaml [Pipe]
|
||||
items[2|]{sku|name|qty|price}:
|
||||
A1|Widget|2|9.99
|
||||
B2|Gadget|1|14.5
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Tab and pipe delimiters are explicitly encoded in the header brackets and field braces. Inside an array scope, only the active delimiter triggers quoting – the others are literal data. Object field values (`key: value`) follow the document delimiter (§11.1) regardless of any surrounding array's active delimiter.
|
||||
|
||||
> [!TIP]
|
||||
> Tab delimiters often tokenize more efficiently than commas, especially for data with few quoted strings. Use `encode(data, { delimiter: '\t' })` for additional token savings.
|
||||
|
||||
## Key Folding (Optional)
|
||||
|
||||
Key folding is an optional encoder feature (since spec v1.5) that collapses chains of single-key objects into dotted paths, reducing tokens for deeply nested data.
|
||||
|
||||
### Basic Folding
|
||||
|
||||
Standard nesting:
|
||||
|
||||
```yaml
|
||||
data:
|
||||
metadata:
|
||||
items[2]: a,b
|
||||
```
|
||||
|
||||
With key folding (`keyFolding: 'safe'`):
|
||||
|
||||
```yaml
|
||||
data.metadata.items[2]: a,b
|
||||
```
|
||||
|
||||
The three nested objects collapse into a single dotted key `data.metadata.items`.
|
||||
|
||||
### When Folding Applies
|
||||
|
||||
A chain of objects is foldable when:
|
||||
- Each object in the chain has exactly one key (leading to the next object or a leaf value)
|
||||
- The leaf value is a primitive, array, or empty object
|
||||
- All segments are valid identifier segments (letters, digits, underscores only; no dots within segments)
|
||||
- The resulting folded key doesn't collide with existing keys
|
||||
|
||||
::: details Advanced Folding Rules
|
||||
**Segment Requirements (safe mode):**
|
||||
- All folded segments must match `^[A-Za-z_][A-Za-z0-9_]*$` (no dots, hyphens, or other special characters)
|
||||
- No segment may require quoting per §7.3 of the spec
|
||||
- The resulting folded key must not equal any existing sibling literal key at the same depth (collision avoidance)
|
||||
|
||||
**Depth Limit:**
|
||||
- The `flattenDepth` option (default: `Infinity`) controls how many segments to fold
|
||||
- `flattenDepth: 2` folds only two-segment chains: `{a: {b: val}}` → `a.b: val`
|
||||
- Values less than 2 have no practical effect
|
||||
|
||||
**Round-Trip with Path Expansion:**
|
||||
To reconstruct the original structure when decoding, use `expandPaths: 'safe'`. This splits dotted keys back into nested objects using the same safety rules ([spec §13.4](https://github.com/toon-format/spec/blob/main/SPEC.md#134-key-folding-and-path-expansion)).
|
||||
:::
|
||||
|
||||
### Round-Trip with Path Expansion
|
||||
|
||||
When decoding TOON that used key folding, enable path expansion to restore the nested structure:
|
||||
|
||||
```ts
|
||||
import { decode, encode } from '@toon-format/toon'
|
||||
|
||||
const original = { data: { metadata: { items: ['a', 'b'] } } }
|
||||
|
||||
// Encode with folding
|
||||
const toon = encode(original, { keyFolding: 'safe' })
|
||||
// → "data.metadata.items[2]: a,b"
|
||||
|
||||
// Decode with expansion
|
||||
const restored = decode(toon, { expandPaths: 'safe' })
|
||||
// → { data: { metadata: { items: ['a', 'b'] } } }
|
||||
```
|
||||
|
||||
Path expansion is off by default, so dotted keys are treated as literal keys unless explicitly enabled.
|
||||
|
||||
## Quoting and Types
|
||||
|
||||
### When Strings Need Quotes
|
||||
|
||||
TOON quotes strings **only when necessary** to maximize token efficiency. A string must be quoted if:
|
||||
|
||||
- It's empty (`""`)
|
||||
- It has leading or trailing whitespace
|
||||
- It equals `true`, `false`, or `null` (case-sensitive)
|
||||
- It looks like a number (e.g., `"42"`, `"-3.14"`, `"1e-6"`, `"05"`)
|
||||
- It contains special characters: colon (`:`), quote (`"`), backslash (`\`), brackets, braces, or any control character in U+0000–U+001F
|
||||
- It contains the relevant delimiter (the active delimiter inside an array scope, or the document delimiter elsewhere)
|
||||
- It equals `"-"` or starts with `"-"` followed by any character
|
||||
|
||||
Otherwise, strings can be unquoted. Unicode, emoji, and strings with internal (non-leading/trailing) spaces are safe unquoted:
|
||||
|
||||
```yaml
|
||||
message: Hello 世界 👋
|
||||
note: This has inner spaces
|
||||
```
|
||||
|
||||
### Escape Sequences
|
||||
|
||||
In quoted strings and keys, six escape sequences are valid:
|
||||
|
||||
| Character | Escape |
|
||||
|-----------|--------|
|
||||
| Backslash (`\`) | `\\` |
|
||||
| Double quote (`"`) | `\"` |
|
||||
| Newline (U+000A) | `\n` |
|
||||
| Carriage return (U+000D) | `\r` |
|
||||
| Tab (U+0009) | `\t` |
|
||||
| Any other U+0000–U+001F control character | `\uXXXX` |
|
||||
|
||||
Other escapes (e.g., `\x`, `\0`, `\b`) are always rejected, as are lone-surrogate `\uXXXX` values (U+D800–U+DFFF).
|
||||
|
||||
### Type Conversions
|
||||
|
||||
Numbers are emitted in canonical decimal form for values in the §2 carve-out range; exponent notation is permitted outside. Non-JSON types (`NaN`, `Infinity`, `BigInt`, `Date`, `Set`, `Map`, `undefined`, etc.) are normalized before encoding – see [API Reference – Type Normalization](/reference/api#type-normalization) for the full mapping.
|
||||
|
||||
Decoders accept both decimal and exponent forms on input (e.g., `42`, `-3.14`, `1e-6`), and treat tokens with forbidden leading zeros (e.g., `"05"`) as strings, not numbers.
|
||||
|
||||
### Custom Serialization with toJSON
|
||||
|
||||
Objects with a `toJSON()` method are serialized by calling the method and normalizing its result before encoding, similar to `JSON.stringify`:
|
||||
|
||||
```ts
|
||||
const obj = {
|
||||
data: 'example',
|
||||
toJSON() {
|
||||
return { info: this.data }
|
||||
}
|
||||
}
|
||||
|
||||
encode(obj)
|
||||
// info: example
|
||||
```
|
||||
|
||||
The `toJSON()` method:
|
||||
|
||||
- Takes precedence over built-in normalization (Date, Array, Set, Map)
|
||||
- Results are recursively normalized
|
||||
- Is called for objects with `toJSON` in their prototype chain
|
||||
|
||||
---
|
||||
|
||||
For complete rules on quoting, escaping, type conversions, and strict-mode decoding, see [spec §2–4 (data model), §7 (strings and keys), and §14 (strict mode)](https://github.com/toon-format/spec/blob/main/SPEC.md).
|
||||
@@ -0,0 +1,248 @@
|
||||
---
|
||||
description: What TOON is, when to use it, and a first encode/decode example with the TypeScript library.
|
||||
---
|
||||
|
||||
# Getting Started
|
||||
|
||||
## What Is TOON?
|
||||
|
||||
**Token-Oriented Object Notation** is a compact, human-readable encoding of the JSON data model that minimizes tokens and makes structure easy for models to follow. It is intended for *LLM input* as a drop-in, lossless representation of your existing JSON.
|
||||
|
||||
TOON combines YAML's indentation-based structure for nested objects with a CSV-style tabular layout for uniform arrays. TOON's sweet spot is uniform arrays of objects (multiple fields per row, same structure across items), achieving CSV-like compactness while adding explicit structure that helps LLMs parse and validate data reliably.
|
||||
|
||||
Think of it as a translation layer: use JSON programmatically, and encode it as TOON for LLM input.
|
||||
|
||||
### Why TOON?
|
||||
|
||||
Standard JSON is verbose and token-expensive. For uniform arrays of objects, JSON repeats every field name for every record:
|
||||
|
||||
```json
|
||||
{
|
||||
"users": [
|
||||
{ "id": 1, "name": "Alice", "role": "admin" },
|
||||
{ "id": 2, "name": "Bob", "role": "user" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
YAML already reduces some redundancy with indentation instead of braces:
|
||||
|
||||
```yaml
|
||||
users:
|
||||
- id: 1
|
||||
name: Alice
|
||||
role: admin
|
||||
- id: 2
|
||||
name: Bob
|
||||
role: user
|
||||
```
|
||||
|
||||
TOON goes further by declaring fields once and streaming data as rows:
|
||||
|
||||
```yaml
|
||||
users[2]{id,name,role}:
|
||||
1,Alice,admin
|
||||
2,Bob,user
|
||||
```
|
||||
|
||||
The `[2]` declares the array length, letting LLMs answer dataset-size questions and detect truncation. The `{id,name,role}` declares the field names. Each row is a compact, comma-separated list of values. The pattern is the same throughout TOON: declare structure once, stream data compactly. The result lands close to CSV density with explicit structure preserved.
|
||||
|
||||
For a more realistic example, here's how TOON handles a dataset with both nested objects and tabular arrays:
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (235 tokens)]
|
||||
{
|
||||
"context": {
|
||||
"task": "Our favorite hikes together",
|
||||
"location": "Boulder",
|
||||
"season": "spring_2025"
|
||||
},
|
||||
"friends": ["ana", "luis", "sam"],
|
||||
"hikes": [
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Blue Lake Trail",
|
||||
"distanceKm": 7.5,
|
||||
"elevationGain": 320,
|
||||
"companion": "ana",
|
||||
"wasSunny": true
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Ridge Overlook",
|
||||
"distanceKm": 9.2,
|
||||
"elevationGain": 540,
|
||||
"companion": "luis",
|
||||
"wasSunny": false
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"name": "Wildflower Loop",
|
||||
"distanceKm": 5.1,
|
||||
"elevationGain": 180,
|
||||
"companion": "sam",
|
||||
"wasSunny": true
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON (106 tokens)]
|
||||
context:
|
||||
task: Our favorite hikes together
|
||||
location: Boulder
|
||||
season: spring_2025
|
||||
friends[3]: ana,luis,sam
|
||||
hikes[3]{id,name,distanceKm,elevationGain,companion,wasSunny}:
|
||||
1,Blue Lake Trail,7.5,320,ana,true
|
||||
2,Ridge Overlook,9.2,540,luis,false
|
||||
3,Wildflower Loop,5.1,180,sam,true
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Notice how TOON combines YAML's indentation for the `context` object with inline format for the primitive `friends` array and tabular format for the structured `hikes` array. Each format is chosen automatically based on the data structure.
|
||||
|
||||
### Design Goals
|
||||
|
||||
TOON is optimized for specific use cases. It aims to:
|
||||
|
||||
- Make uniform arrays of objects as compact as possible by declaring structure once and streaming data.
|
||||
- Stay fully lossless and deterministic – round-trips preserve all data and structure.
|
||||
- Keep parsing simple and robust for both LLMs and humans through explicit structure markers.
|
||||
- Provide validation guardrails (array lengths, field counts) that help detect truncation and malformed output.
|
||||
|
||||
## When to Use TOON
|
||||
|
||||
TOON excels with uniform arrays of objects – data with the same structure across items. For LLM prompts, the format produces deterministic, minimally quoted text with built-in validation. Explicit array lengths (`[N]`) and field headers (`{fields}`) help detect truncation and malformed data, while the tabular structure declares fields once rather than repeating them in every row.
|
||||
|
||||
::: tip
|
||||
The TOON format is stable, but also an idea in progress. Nothing's set in stone – help shape where it goes by contributing to the [spec](https://github.com/toon-format/spec) or sharing feedback.
|
||||
:::
|
||||
|
||||
## When Not to Use TOON
|
||||
|
||||
TOON is not always the best choice. Consider alternatives when:
|
||||
|
||||
- **Deeply nested or non-uniform structures** (tabular eligibility ≈ 0%): JSON-compact often uses fewer tokens. Example: complex configuration objects with many nested levels.
|
||||
- **Semi-uniform arrays** (~40–60% tabular eligibility): Token savings diminish. Prefer JSON if your pipelines already rely on it.
|
||||
- **Pure tabular data**: CSV is smaller than TOON for flat tables. TOON adds minimal overhead (~5–10%) to provide structure (array length declarations, field headers, delimiter scoping) that improves LLM reliability.
|
||||
- **Latency-critical applications**: Benchmark on your exact setup. Some deployments (especially local/quantized models) may process compact JSON faster despite TOON's lower token count.
|
||||
|
||||
::: info
|
||||
For data-driven comparisons across different structures, see [Benchmarks](/guide/benchmarks). When optimizing for latency, measure TTFT, tokens/sec, and total time for both TOON and JSON-compact, and use whichever is faster in your specific environment.
|
||||
:::
|
||||
|
||||
## Installation
|
||||
|
||||
### TypeScript Library
|
||||
|
||||
Install the library via your preferred package manager:
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [npm]
|
||||
npm install @toon-format/toon
|
||||
```
|
||||
|
||||
```bash [pnpm]
|
||||
pnpm add @toon-format/toon
|
||||
```
|
||||
|
||||
```bash [yarn]
|
||||
yarn add @toon-format/toon
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### CLI
|
||||
|
||||
The CLI can be used without installation via `npx`, or installed globally:
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [npx (no install)]
|
||||
npx @toon-format/cli input.json -o output.toon
|
||||
```
|
||||
|
||||
```bash [npm]
|
||||
npm install -g @toon-format/cli
|
||||
```
|
||||
|
||||
```bash [pnpm]
|
||||
pnpm add -g @toon-format/cli
|
||||
```
|
||||
|
||||
```bash [yarn]
|
||||
yarn global add @toon-format/cli
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
For full CLI documentation, see the [CLI reference](/cli/).
|
||||
|
||||
## Media Type & File Extension
|
||||
|
||||
TOON files conventionally use the `.toon` extension. For HTTP transmission, the provisional media type is `text/toon`, always with UTF-8 encoding. While you may specify `charset=utf-8` explicitly, it's optional – UTF-8 is the default assumption. This follows the registration process outlined in [spec §17](https://github.com/toon-format/spec/blob/main/SPEC.md#17-iana-considerations).
|
||||
|
||||
## Your First Example
|
||||
|
||||
The examples below use the TypeScript library for demonstration, but the same operations work in any language with a TOON implementation.
|
||||
|
||||
Let's encode a simple dataset with the TypeScript library:
|
||||
|
||||
```ts
|
||||
import { encode } from '@toon-format/toon'
|
||||
|
||||
const data = {
|
||||
users: [
|
||||
{ id: 1, name: 'Alice', role: 'admin' },
|
||||
{ id: 2, name: 'Bob', role: 'user' }
|
||||
]
|
||||
}
|
||||
|
||||
console.log(encode(data))
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```yaml
|
||||
users[2]{id,name,role}:
|
||||
1,Alice,admin
|
||||
2,Bob,user
|
||||
```
|
||||
|
||||
### Decoding Back to JSON
|
||||
|
||||
Decoding is just as simple:
|
||||
|
||||
```ts
|
||||
import { decode } from '@toon-format/toon'
|
||||
|
||||
const toon = `
|
||||
users[2]{id,name,role}:
|
||||
1,Alice,admin
|
||||
2,Bob,user
|
||||
`
|
||||
|
||||
const data = decode(toon)
|
||||
console.log(JSON.stringify(data, null, 2))
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```json
|
||||
{
|
||||
"users": [
|
||||
{ "id": 1, "name": "Alice", "role": "admin" },
|
||||
{ "id": 2, "name": "Bob", "role": "user" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Round-tripping is lossless: `decode(encode(x))` always equals `x` (after normalization of non-JSON types like `Date`, `NaN`, etc.).
|
||||
|
||||
## Where to Go Next
|
||||
|
||||
Now that you've seen your first TOON document, read the [Format Overview](/guide/format-overview) for complete syntax details (objects, arrays, quoting rules, key folding), then explore [Using TOON with LLMs](/guide/llm-prompts) to see how to use it effectively in prompts. For implementation details, check the [API Reference](/reference/api) (TypeScript) or the [Specification](/reference/spec) (language-agnostic normative rules).
|
||||
@@ -0,0 +1,191 @@
|
||||
---
|
||||
description: Prompting strategies for sending TOON to LLMs and validating TOON they generate, with examples.
|
||||
---
|
||||
|
||||
# Using TOON with LLMs
|
||||
|
||||
TOON is designed for passing structured data to Large Language Models with reduced token costs and improved reliability. This guide shows how to use TOON effectively in prompts, both for input (sending data to models) and output (getting models to generate TOON).
|
||||
|
||||
This guide is about the TOON format itself. Code examples use the TypeScript library for demonstration, but the same patterns and techniques apply regardless of which programming language you're using.
|
||||
|
||||
## Why TOON for LLMs
|
||||
|
||||
LLM tokens cost money, and JSON is verbose – repeating every field name for every record in an array. TOON minimizes tokens especially for uniform arrays by declaring fields once and streaming data as rows, typically saving 30–60% compared to formatted JSON.
|
||||
|
||||
TOON adds structure guardrails: explicit `[N]` lengths and `{fields}` headers make it easier for models to track rows and for you to validate output. Strict mode helps detect truncation and malformed TOON when decoding model responses.
|
||||
|
||||
## Sending TOON as Input
|
||||
|
||||
TOON works best when you show the format instead of describing it. The structure is self-documenting – models parse it naturally once they see the pattern.
|
||||
|
||||
Wrap your encoded data in a fenced code block (label it ` ```toon` for clarity):
|
||||
|
||||
````md
|
||||
Data is in TOON format (2-space indent, arrays show length and fields).
|
||||
|
||||
```toon
|
||||
users[3]{id,name,role,lastLogin}:
|
||||
1,Alice,admin,"2025-01-15T10:30:00Z"
|
||||
2,Bob,user,"2025-01-14T15:22:00Z"
|
||||
3,Charlie,user,"2025-01-13T09:45:00Z"
|
||||
```
|
||||
|
||||
Task: Summarize the user roles and their last activity.
|
||||
````
|
||||
|
||||
The indentation and headers are usually enough – models treat TOON like familiar YAML or CSV. The explicit array lengths (`[N]`) and field headers (`{fields}`) help the model track structure, especially for large tables.
|
||||
|
||||
> [!NOTE]
|
||||
> Most models don't have built-in TOON syntax highlighting, so ` ```toon` or ` ```yaml` both work fine. The structure is what matters.
|
||||
|
||||
## Generating TOON from LLMs
|
||||
|
||||
For output, be more explicit. When you want the model to **generate** TOON:
|
||||
|
||||
- **Show the expected header** (e.g., `users[N]{id,name,role}:`). The model fills rows instead of repeating keys, reducing generation errors.
|
||||
- **State the rules**: 2-space indent, no trailing spaces, `[N]` matches row count.
|
||||
|
||||
Here's a prompt that works for both reading and generating:
|
||||
|
||||
````md
|
||||
Data is in TOON format (2-space indent, arrays show length and fields).
|
||||
|
||||
```toon
|
||||
users[3]{id,name,role,lastLogin}:
|
||||
1,Alice,admin,"2025-01-15T10:30:00Z"
|
||||
2,Bob,user,"2025-01-14T15:22:00Z"
|
||||
3,Charlie,user,"2025-01-13T09:45:00Z"
|
||||
```
|
||||
|
||||
Task: Return only users with role "user" as TOON. Use the same header format. Set [N] to match the row count. Output only the code block.
|
||||
````
|
||||
|
||||
**Expected output:**
|
||||
|
||||
```toon
|
||||
users[2]{id,name,role,lastLogin}:
|
||||
2,Bob,user,"2025-01-14T15:22:00Z"
|
||||
3,Charlie,user,"2025-01-13T09:45:00Z"
|
||||
```
|
||||
|
||||
The model adjusts `[N]` to `2` and generates two rows.
|
||||
|
||||
### Validation with Strict Mode
|
||||
|
||||
When decoding model-generated TOON, use strict mode (default) to catch errors:
|
||||
|
||||
```ts
|
||||
import { decode } from '@toon-format/toon'
|
||||
|
||||
try {
|
||||
const data = decode(modelOutput, { strict: true })
|
||||
// Success – data is valid
|
||||
}
|
||||
catch (error) {
|
||||
// Model output was malformed (count mismatch, invalid escapes, etc.)
|
||||
console.error('Validation failed:', error.message)
|
||||
}
|
||||
```
|
||||
|
||||
Strict mode checks counts, indentation, and escaping so you can detect truncation or malformed TOON. For complete details, see the [API Reference](/reference/api#decode-input-options).
|
||||
|
||||
## Delimiter Choices for Token Efficiency
|
||||
|
||||
Use `delimiter: '\t'` for tab-separated tables if you want even fewer tokens. Tabs are single characters, often tokenize more efficiently than commas, and rarely appear in natural text (reducing quote-escaping).
|
||||
|
||||
```ts
|
||||
const toon = encode(data, { delimiter: '\t' })
|
||||
```
|
||||
|
||||
Tell the model "fields are tab-separated" when using tabs. For more on delimiters, see the [Format Overview](/guide/format-overview#delimiter-options).
|
||||
|
||||
## Streaming Large Outputs
|
||||
|
||||
When working with large datasets (thousands of records or deeply nested structures), use `encodeLines()` to stream TOON output line-by-line instead of building the full string in memory.
|
||||
|
||||
```ts
|
||||
import { encodeLines } from '@toon-format/toon'
|
||||
|
||||
const largeData = await fetchThousandsOfRecords()
|
||||
|
||||
// Stream large dataset without loading full string in memory
|
||||
for (const line of encodeLines(largeData, { delimiter: '\t' })) {
|
||||
process.stdout.write(`${line}\n`)
|
||||
}
|
||||
```
|
||||
|
||||
The CLI also supports streaming for memory-efficient JSON-to-TOON conversion:
|
||||
|
||||
```bash
|
||||
toon large-dataset.json -o output.toon
|
||||
```
|
||||
|
||||
This streaming approach prevents out-of-memory errors when preparing large context windows for LLMs. For complete details on `encodeLines()`, see the [API Reference](/reference/api#encodelines-input-options).
|
||||
|
||||
**Consuming streaming LLM outputs:** If your LLM client exposes streaming text and you buffer by lines, you can decode TOON incrementally:
|
||||
|
||||
```ts
|
||||
import { decodeFromLines } from '@toon-format/toon'
|
||||
|
||||
// Buffer streaming response into lines
|
||||
const lines: string[] = []
|
||||
let buffer = ''
|
||||
|
||||
for await (const chunk of modelStream) {
|
||||
buffer += chunk
|
||||
let index: number
|
||||
|
||||
while ((index = buffer.indexOf('\n')) !== -1) {
|
||||
lines.push(buffer.slice(0, index))
|
||||
buffer = buffer.slice(index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
// Decode buffered lines
|
||||
const data = decodeFromLines(lines)
|
||||
```
|
||||
|
||||
For streaming decode APIs, see [`decodeFromLines()`](/reference/api#decodefromlines-lines-options) and [`decodeStream()`](/reference/api#decodestream-source-options).
|
||||
|
||||
## Tips and Pitfalls
|
||||
|
||||
**Show, don't describe.** Don't explain TOON syntax in detail – just show an example. Models learn the pattern from context. A simple code block with 2–5 rows is more effective than paragraphs of explanation.
|
||||
|
||||
**Keep examples small.** Use 2–5 rows in your examples, not hundreds. The model generalizes from the pattern. Large examples waste tokens without improving accuracy.
|
||||
|
||||
**Always validate output.** Decode generated TOON with `strict: true` (default) to catch errors early. Don't assume model output is valid TOON without checking.
|
||||
|
||||
## Real-World Example
|
||||
|
||||
Here's a complete workflow: send data to a model and validate its TOON response.
|
||||
|
||||
**Prompt with TOON input:**
|
||||
|
||||
````md
|
||||
System logs in TOON format (tab-separated):
|
||||
|
||||
```toon
|
||||
events[4 ]{id level message timestamp}:
|
||||
1 error Connection timeout "2025-01-15T10:00:00Z"
|
||||
2 warn Slow query "2025-01-15T10:05:00Z"
|
||||
3 info User login "2025-01-15T10:10:00Z"
|
||||
4 error Database error "2025-01-15T10:15:00Z"
|
||||
```
|
||||
|
||||
Task: Return only error-level events as TOON. Use the same format.
|
||||
````
|
||||
|
||||
**Validate the response:**
|
||||
|
||||
```ts
|
||||
import { decode } from '@toon-format/toon'
|
||||
|
||||
const modelResponse = `
|
||||
events[2 ]{id level message timestamp}:
|
||||
1 error Connection timeout "2025-01-15T10:00:00Z"
|
||||
4 error Database error "2025-01-15T10:15:00Z"
|
||||
`
|
||||
|
||||
const filtered = decode(modelResponse, { strict: true })
|
||||
// ✓ Validated – model correctly filtered and adjusted [N] to 2
|
||||
```
|
||||
@@ -0,0 +1,51 @@
|
||||
---
|
||||
layout: home
|
||||
titleTemplate: Token-Oriented Object Notation
|
||||
hero:
|
||||
name: TOON
|
||||
text: Token-Oriented Object Notation
|
||||
tagline: A compact, human-readable encoding of the JSON data model for LLM prompts.
|
||||
image:
|
||||
dark: /logo-index-dark.svg
|
||||
light: /logo-index-light.svg
|
||||
alt: TOON Logo
|
||||
actions:
|
||||
- theme: brand
|
||||
text: What is TOON?
|
||||
link: /guide/getting-started
|
||||
- theme: alt
|
||||
text: Benchmarks
|
||||
link: /guide/benchmarks
|
||||
- theme: alt
|
||||
text: Playground
|
||||
link: /playground
|
||||
- theme: alt
|
||||
text: CLI
|
||||
link: /cli/
|
||||
|
||||
features:
|
||||
- title: Token-Efficient & Accurate
|
||||
icon: 📊
|
||||
details: TOON reaches 76.4% accuracy (vs JSON's 75.0%) while using ~40% fewer tokens in mixed-structure benchmarks across 4 models.
|
||||
link: /guide/benchmarks
|
||||
- title: JSON Data Model
|
||||
icon: 🔁
|
||||
details: Encodes the same objects, arrays, and primitives as JSON with deterministic, lossless round-trips.
|
||||
link: /guide/format-overview
|
||||
- title: LLM-Friendly Guardrails
|
||||
icon: 🛤️
|
||||
details: Explicit [N] lengths and {fields} headers give models a clear schema to follow, improving parsing reliability.
|
||||
link: /guide/format-overview#arrays
|
||||
- title: Minimal Syntax
|
||||
icon: 📐
|
||||
details: Uses indentation instead of braces and minimizes quoting, giving YAML-like readability with CSV-style compactness.
|
||||
link: /guide/format-overview#arrays
|
||||
- title: Tabular Arrays
|
||||
icon: 🧺
|
||||
details: Uniform arrays of objects collapse into tables that declare fields once and stream row values line by line.
|
||||
link: /guide/format-overview#arrays
|
||||
- title: Multi-Language Ecosystem
|
||||
icon: 🌐
|
||||
details: Spec-driven implementations in TypeScript, Python, Go, Rust, .NET, and other languages.
|
||||
link: /ecosystem/implementations
|
||||
---
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "@toon-format/docs",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vitepress dev",
|
||||
"build": "vitepress build",
|
||||
"preview": "vitepress preview"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vueuse/core": "^14.3.0",
|
||||
"fflate": "^0.8.3",
|
||||
"gpt-tokenizer": "^3.4.0",
|
||||
"markdown-it-mathjax3": "^4.3.2",
|
||||
"uint8array-extras": "^1.5.0",
|
||||
"unocss": "^66.6.8",
|
||||
"vitepress": "^1.6.4",
|
||||
"vitepress-plugin-llms": "^1.12.2",
|
||||
"yaml": "^2.9.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
layout: PlaygroundLayout
|
||||
title: Playground
|
||||
---
|
||||
|
After Width: | Height: | Size: 5.3 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 180 180"><g clip-path="url(#a)"><path fill="#fef3c0" d="M0 59.76C0 10.548 10.548 0 59.76 0h60.48C169.452 0 180 10.548 180 59.76v60.48c0 49.212-10.548 59.76-59.76 59.76H59.76C10.548 180 0 169.452 0 120.24z"/><path fill="#fff" d="M120 40h20v20h-20z"/><path fill="#1b1b1f" d="M160 80h-60V20h60zm-40-20h20V40h-20zM140 100v20h-20v40h-20v-60zm20 60h-20v-40h20z"/><path fill="#fff" d="M40 120h20v20H40z"/><path fill="#1b1b1f" d="M80 160H20v-60h60zm-40-20h20v-20H40zM60 80H40V40H20V20h60v20H60z"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h180v180H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 645 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 180 180"><g fill="#fff" clip-path="url(#a)"><path d="M180 77.143h-77.143V0H180zm-51.429-25.714h25.715V25.714h-25.715zM154.286 102.857v25.714h-25.715V180h-25.714v-77.143zM180 180h-25.714v-51.429H180zM77.143 180H0v-77.143h77.143zm-51.429-25.714h25.715v-25.715H25.714zM51.429 77.143H25.714V25.714H0V0h77.143v25.714H51.429z"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h180v180H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 478 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 180 180"><g fill="#1b1b1f" clip-path="url(#a)"><path d="M180 77.143h-77.143V0H180zm-51.429-25.714h25.715V25.714h-25.715zM154.286 102.857v25.714h-25.715V180h-25.714v-77.143zM180 180h-25.714v-51.429H180zM77.143 180H0v-77.143h77.143zm-51.429-25.714h25.715v-25.715H25.714zM51.429 77.143H25.714V25.714H0V0h77.143v25.714H51.429z"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h180v180H0z"/></clipPath></defs></svg>
|
||||
|
After Width: | Height: | Size: 481 B |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 180 180"><path fill="#fef3c0" d="M0 0h180v180H0z"/><path fill="#fff" d="M120 40h20v20h-20z"/><path fill="#1b1b1f" d="M160 80h-60V20h60zm-40-20h20V40h-20zM140 100v20h-20v40h-20v-60zm20 60h-20v-40h20z"/><path fill="#fff" d="M40 120h20v20H40z"/><path fill="#1b1b1f" d="M80 160H20v-60h60zm-40-20h20v-20H40zM60 80H40V40H20V20h60v20H60z"/></svg>
|
||||
|
After Width: | Height: | Size: 405 B |
|
After Width: | Height: | Size: 38 KiB |
|
After Width: | Height: | Size: 17 KiB |
@@ -0,0 +1,766 @@
|
||||
---
|
||||
description: TypeScript and JavaScript encode and decode functions, options, error types, and streaming decoders for @toon-format/toon.
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
TypeScript/JavaScript API documentation for the `@toon-format/toon` package. For format rules, see the [Format Overview](/guide/format-overview) or the [Specification](/reference/spec). For other languages, see [Implementations](/ecosystem/implementations).
|
||||
|
||||
## Installation
|
||||
|
||||
::: code-group
|
||||
|
||||
```bash [npm]
|
||||
npm install @toon-format/toon
|
||||
```
|
||||
|
||||
```bash [pnpm]
|
||||
pnpm add @toon-format/toon
|
||||
```
|
||||
|
||||
```bash [yarn]
|
||||
yarn add @toon-format/toon
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Encoding Functions
|
||||
|
||||
### `encode(input, options?)`
|
||||
|
||||
Converts any JSON-serializable value to TOON format.
|
||||
|
||||
```ts
|
||||
import { encode } from '@toon-format/toon'
|
||||
|
||||
const toon = encode(data, {
|
||||
indent: 2,
|
||||
delimiter: ',',
|
||||
keyFolding: 'off',
|
||||
flattenDepth: Infinity
|
||||
})
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `input` | `unknown` | Any JSON-serializable value (object, array, primitive, or nested structure) |
|
||||
| `options` | `EncodeOptions?` | Optional encoding options (see [Configuration Reference](#configuration-reference)) |
|
||||
|
||||
#### Return Value
|
||||
|
||||
Returns a TOON-formatted string with no trailing newline or spaces.
|
||||
|
||||
#### Type Normalization
|
||||
|
||||
Non-JSON-serializable values are normalized before encoding:
|
||||
|
||||
| Input | Output |
|
||||
|-------|--------|
|
||||
| `Object` with `toJSON()` method | Result of calling `toJSON()`, recursively normalized |
|
||||
| Finite number in `[1e-6, 1e21)` (or zero) | Canonical decimal (e.g., `1e6` → `1000000`, `-0` → `0`) |
|
||||
| Finite number outside that range | Exponent form permitted (e.g., `1e-7`, `1e+21`) |
|
||||
| `NaN`, `Infinity`, `-Infinity` | `null` |
|
||||
| `BigInt` (within safe range) | Number |
|
||||
| `BigInt` (out of range) | Quoted decimal string (e.g., `"9007199254740993"`) |
|
||||
| `Date` | ISO string in quotes (e.g., `"2025-01-01T00:00:00.000Z"`) |
|
||||
| `Set` | Array of normalized values |
|
||||
| `Map` | Object with `String(key)` keys |
|
||||
| `undefined`, `function`, `symbol` | `null` |
|
||||
|
||||
::: info
|
||||
TOON itself doesn't specify how `Date` should be encoded – the spec leaves this to implementations. This library emits an ISO 8601 string in quotes; other implementations may choose differently.
|
||||
:::
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
import { encode } from '@toon-format/toon'
|
||||
|
||||
const items = [
|
||||
{ sku: 'A1', qty: 2, price: 9.99 },
|
||||
{ sku: 'B2', qty: 1, price: 14.5 }
|
||||
]
|
||||
|
||||
console.log(encode({ items }))
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```yaml
|
||||
items[2]{sku,qty,price}:
|
||||
A1,2,9.99
|
||||
B2,1,14.5
|
||||
```
|
||||
|
||||
### `encodeLines(input, options?)`
|
||||
|
||||
**Preferred method for streaming TOON output.** Converts any JSON-serializable value to TOON format as a sequence of lines, without building the full string in memory. Suitable for streaming large outputs to files, HTTP responses, or process stdout.
|
||||
|
||||
```ts
|
||||
import { encodeLines } from '@toon-format/toon'
|
||||
|
||||
// Stream to stdout (Node.js)
|
||||
for (const line of encodeLines(data)) {
|
||||
process.stdout.write(`${line}\n`)
|
||||
}
|
||||
|
||||
// Write to file line-by-line
|
||||
const lines = encodeLines(data, { indent: 2, delimiter: '\t' })
|
||||
for (const line of lines) {
|
||||
await writeToStream(`${line}\n`)
|
||||
}
|
||||
|
||||
// Collect to array
|
||||
const lineArray = Array.from(encodeLines(data))
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `input` | `unknown` | Any JSON-serializable value (object, array, primitive, or nested structure) |
|
||||
| `options` | `EncodeOptions?` | Optional encoding options (see [Configuration Reference](#configuration-reference)) |
|
||||
|
||||
#### Return Value
|
||||
|
||||
Returns an `Iterable<string>` that yields TOON lines one at a time. **Each yielded string is a single line without a trailing newline character** – you must add `\n` when writing to streams or stdout.
|
||||
|
||||
::: info Relationship to `encode()`
|
||||
`encode(value, options)` is equivalent to:
|
||||
```ts
|
||||
Array.from(encodeLines(value, options)).join('\n')
|
||||
```
|
||||
:::
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
import { createWriteStream } from 'node:fs'
|
||||
import { encodeLines } from '@toon-format/toon'
|
||||
|
||||
const data = {
|
||||
items: Array.from({ length: 100000 }, (_, i) => ({
|
||||
id: i,
|
||||
name: `Item ${i}`,
|
||||
value: Math.random()
|
||||
}))
|
||||
}
|
||||
|
||||
// Stream large dataset to file
|
||||
const stream = createWriteStream('output.toon')
|
||||
for (const line of encodeLines(data, { delimiter: '\t' })) {
|
||||
stream.write(`${line}\n`)
|
||||
}
|
||||
stream.end()
|
||||
```
|
||||
|
||||
### Replacer Function
|
||||
|
||||
The `replacer` option allows you to transform or filter values during encoding. It works similarly to `JSON.stringify`'s replacer parameter, but with path tracking for more precise control.
|
||||
|
||||
#### Type Signature
|
||||
|
||||
```typescript
|
||||
type EncodeReplacer = (
|
||||
key: string,
|
||||
value: JsonValue,
|
||||
path: readonly (string | number)[]
|
||||
) => unknown
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `key` | `string` | Property name, array index (as string), or empty string for root |
|
||||
| `value` | `JsonValue` | The normalized value at this location |
|
||||
| `path` | `readonly (string \| number)[]` | Path from root to current value |
|
||||
|
||||
#### Return Value
|
||||
|
||||
- Return the value unchanged to keep it
|
||||
- Return a different value to replace it (will be normalized)
|
||||
- Return `undefined` to omit properties/array elements
|
||||
- For root value, `undefined` means "no change" (root cannot be omitted)
|
||||
|
||||
#### Examples
|
||||
|
||||
**Filtering sensitive data:**
|
||||
|
||||
```typescript
|
||||
import { encode } from '@toon-format/toon'
|
||||
|
||||
const data = {
|
||||
user: { name: 'Alice', password: 'secret123', email: 'alice@example.com' }
|
||||
}
|
||||
|
||||
function replacer(key, value) {
|
||||
if (key === 'password')
|
||||
return undefined
|
||||
return value
|
||||
}
|
||||
|
||||
console.log(encode(data, { replacer }))
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```yaml
|
||||
user:
|
||||
name: Alice
|
||||
email: alice@example.com
|
||||
```
|
||||
|
||||
**Transforming values:**
|
||||
|
||||
```typescript
|
||||
const data = { user: 'alice', role: 'admin' }
|
||||
|
||||
function replacer(key, value) {
|
||||
if (typeof value === 'string')
|
||||
return value.toUpperCase()
|
||||
return value
|
||||
}
|
||||
|
||||
console.log(encode(data, { replacer }))
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```yaml
|
||||
user: ALICE
|
||||
role: ADMIN
|
||||
```
|
||||
|
||||
**Path-based transformations:**
|
||||
|
||||
```typescript
|
||||
const data = {
|
||||
metadata: { created: '2025-01-01' },
|
||||
user: { created: '2025-01-02' }
|
||||
}
|
||||
|
||||
function replacer(key, value, path) {
|
||||
// Add timezone info only to top-level metadata
|
||||
if (path.length === 1 && path[0] === 'metadata' && key === 'created') {
|
||||
return `${value}T00:00:00Z`
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
console.log(encode(data, { replacer }))
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```yaml
|
||||
metadata:
|
||||
created: "2025-01-01T00:00:00Z"
|
||||
user:
|
||||
created: 2025-01-02
|
||||
```
|
||||
|
||||
::: info Replacer Execution Order
|
||||
The replacer is called in a depth-first manner:
|
||||
1. Root value first (key = `''`, path = `[]`)
|
||||
2. Then each property/element (with proper key and path)
|
||||
3. Values are re-normalized after replacement
|
||||
4. Children are processed after parent transformation
|
||||
:::
|
||||
|
||||
::: warning Array Indices as Strings
|
||||
Following `JSON.stringify` behavior, array indices are passed as strings (`'0'`, `'1'`, `'2'`, etc.) to the replacer, not as numbers.
|
||||
:::
|
||||
|
||||
## Decoding Functions
|
||||
|
||||
### `decode(input, options?)`
|
||||
|
||||
Converts a TOON-formatted string back to JavaScript values.
|
||||
|
||||
```ts
|
||||
import { decode } from '@toon-format/toon'
|
||||
|
||||
const data = decode(toon, {
|
||||
indent: 2,
|
||||
strict: true,
|
||||
expandPaths: 'off'
|
||||
})
|
||||
```
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `input` | `string` | A TOON-formatted string to parse |
|
||||
| `options` | `DecodeOptions?` | Optional decoding options (see [Configuration Reference](#configuration-reference)) |
|
||||
|
||||
#### Return Value
|
||||
|
||||
Returns a JavaScript value (object, array, or primitive) representing the parsed TOON data.
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
import { decode } from '@toon-format/toon'
|
||||
|
||||
const toon = `
|
||||
items[2]{sku,qty,price}:
|
||||
A1,2,9.99
|
||||
B2,1,14.5
|
||||
`
|
||||
|
||||
const data = decode(toon)
|
||||
console.log(data)
|
||||
```
|
||||
|
||||
**Output:**
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{ "sku": "A1", "qty": 2, "price": 9.99 },
|
||||
{ "sku": "B2", "qty": 1, "price": 14.5 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### `decodeFromLines(lines, options?)`
|
||||
|
||||
Decodes TOON format from pre-split lines into a JavaScript value. This is a streaming-friendly wrapper around the event-based decoder that builds the full value in memory.
|
||||
|
||||
Useful when you already have lines as an array or iterable (e.g., from file streams, readline interfaces, or network responses) and want the standard decode behavior with path expansion support.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `lines` | `Iterable<string>` | Iterable of TOON lines (without trailing newlines) |
|
||||
| `options` | `DecodeOptions?` | Optional decoding configuration (see [Configuration Reference](#configuration-reference)) |
|
||||
|
||||
#### Return Value
|
||||
|
||||
Returns a `JsonValue` (the parsed JavaScript value: object, array, or primitive).
|
||||
|
||||
#### Example
|
||||
|
||||
**Basic usage with arrays:**
|
||||
|
||||
```ts
|
||||
import { decodeFromLines } from '@toon-format/toon'
|
||||
|
||||
const lines = ['name: Alice', 'age: 30']
|
||||
const value = decodeFromLines(lines)
|
||||
// { name: 'Alice', age: 30 }
|
||||
```
|
||||
|
||||
**Streaming from Node.js readline:**
|
||||
|
||||
```ts
|
||||
import { createReadStream } from 'node:fs'
|
||||
import { createInterface } from 'node:readline'
|
||||
import { decodeFromLines } from '@toon-format/toon'
|
||||
|
||||
const rl = createInterface({
|
||||
input: createReadStream('data.toon'),
|
||||
crlfDelay: Infinity,
|
||||
})
|
||||
|
||||
const value = decodeFromLines(rl)
|
||||
console.log(value)
|
||||
```
|
||||
|
||||
**With path expansion:**
|
||||
|
||||
```ts
|
||||
const lines = ['user.name: Alice', 'user.age: 30']
|
||||
const value = decodeFromLines(lines, { expandPaths: 'safe' })
|
||||
// { user: { name: 'Alice', age: 30 } }
|
||||
```
|
||||
|
||||
### Choosing the Right Decoder
|
||||
|
||||
| Function | Input | Output | Async | Path Expansion | Use When |
|
||||
|----------|-------|--------|-------|----------------|----------|
|
||||
| `decode()` | String | Value | No | Yes | You have a complete TOON string |
|
||||
| `decodeFromLines()` | Lines | Value | No | Yes | You have lines and want the full value |
|
||||
| `decodeStreamSync()` | Lines | Events | No | No | You need event-by-event processing (sync) |
|
||||
| `decodeStream()` | Lines | Events | Yes | No | You need event-by-event processing (async) |
|
||||
|
||||
::: info Key Differences
|
||||
- **Value vs. Events**: Functions ending in `Stream` yield events without building the full value in memory.
|
||||
- **Path expansion**: Only `decode()` and `decodeFromLines()` support `expandPaths: 'safe'`.
|
||||
- **Async support**: Only `decodeStream()` accepts async iterables (useful for file/network streams).
|
||||
:::
|
||||
|
||||
## Streaming Decoders
|
||||
|
||||
### `decodeStreamSync(lines, options?)`
|
||||
|
||||
Synchronously decodes TOON lines into a stream of JSON events. This function yields structured events that represent the JSON data model without building the full value tree.
|
||||
|
||||
Useful for streaming processing, custom transformations, or memory-efficient parsing of large datasets where you don't need the full value in memory.
|
||||
|
||||
::: tip Event Streaming
|
||||
This is a low-level API that returns individual parse events. For most use cases, [`decodeFromLines()`](#decodefromlines-lines-options) or [`decode()`](#decode-input-options) are more convenient.
|
||||
|
||||
Path expansion (`expandPaths: 'safe'`) is **not supported** in streaming mode since it requires the full value tree.
|
||||
:::
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `lines` | `Iterable<string>` | Iterable of TOON lines (without trailing newlines) |
|
||||
| `options` | `DecodeStreamOptions?` | Optional streaming decoding configuration (see [Configuration Reference](#configuration-reference)) |
|
||||
|
||||
#### Return Value
|
||||
|
||||
Returns an `Iterable<JsonStreamEvent>` that yields structured events (see [TypeScript Types](#typescript-types) for event structure).
|
||||
|
||||
#### Example
|
||||
|
||||
**Basic event streaming:**
|
||||
|
||||
```ts
|
||||
import { decodeStreamSync } from '@toon-format/toon'
|
||||
|
||||
const lines = ['name: Alice', 'age: 30']
|
||||
|
||||
for (const event of decodeStreamSync(lines)) {
|
||||
console.log(event)
|
||||
}
|
||||
|
||||
// Output:
|
||||
// { type: 'startObject' }
|
||||
// { type: 'key', key: 'name' }
|
||||
// { type: 'primitive', value: 'Alice' }
|
||||
// { type: 'key', key: 'age' }
|
||||
// { type: 'primitive', value: 30 }
|
||||
// { type: 'endObject' }
|
||||
```
|
||||
|
||||
**Custom processing:**
|
||||
|
||||
```ts
|
||||
import { decodeStreamSync } from '@toon-format/toon'
|
||||
|
||||
const lines = ['users[2]{id,name}:', ' 1,Alice', ' 2,Bob']
|
||||
let userCount = 0
|
||||
|
||||
for (const event of decodeStreamSync(lines)) {
|
||||
if (event.type === 'endObject' && userCount < 2) {
|
||||
userCount++
|
||||
console.log(`Processed user ${userCount}`)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `decodeStream(source, options?)`
|
||||
|
||||
Asynchronously decodes TOON lines into a stream of JSON events. This is the async version of [`decodeStreamSync()`](#decodestreamsync-lines-options), supporting both synchronous and asynchronous iterables.
|
||||
|
||||
Useful for processing file streams, network responses, or other async sources where you want to handle data incrementally as it arrives.
|
||||
|
||||
#### Parameters
|
||||
|
||||
| Parameter | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `source` | `AsyncIterable<string>` \| `Iterable<string>` | Async or sync iterable of TOON lines (without trailing newlines) |
|
||||
| `options` | `DecodeStreamOptions?` | Optional streaming decoding configuration (see [Configuration Reference](#configuration-reference)) |
|
||||
|
||||
#### Return Value
|
||||
|
||||
Returns an `AsyncIterable<JsonStreamEvent>` that yields structured events asynchronously (see [TypeScript Types](#typescript-types) for event structure).
|
||||
|
||||
#### Example
|
||||
|
||||
**Streaming from file:**
|
||||
|
||||
```ts
|
||||
import { createReadStream } from 'node:fs'
|
||||
import { createInterface } from 'node:readline'
|
||||
import { decodeStream } from '@toon-format/toon'
|
||||
|
||||
const fileStream = createReadStream('data.toon', 'utf-8')
|
||||
const rl = createInterface({ input: fileStream, crlfDelay: Infinity })
|
||||
|
||||
for await (const event of decodeStream(rl)) {
|
||||
console.log(event)
|
||||
// Process events as they arrive
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
Decoding throws a `ToonDecodeError` when input cannot be parsed. The class extends `SyntaxError`, so existing `error instanceof SyntaxError` checks keep working without code changes.
|
||||
|
||||
### `ToonDecodeError`
|
||||
|
||||
```ts
|
||||
import { ToonDecodeError } from '@toon-format/toon'
|
||||
```
|
||||
|
||||
#### Fields
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `name` | `'ToonDecodeError'` | Discriminator – `error.name === 'ToonDecodeError'` |
|
||||
| `message` | `string` | Human-readable message; prefixed with `Line N: ` when a line is known |
|
||||
| `line` | `number?` | 1-based line number where the error was detected |
|
||||
| `source` | `string?` | Raw source line (including its leading whitespace) |
|
||||
| `cause` | `unknown?` | The original error when the decoder enriched a lower-level parser failure |
|
||||
|
||||
The `line` and `source` fields are populated for every error that has line context – essentially every parse error during normal decoding. The `cause` chain points back to the underlying `SyntaxError` or `TypeError` thrown by the token-level parser, so debuggers and verbose loggers can show the original frame.
|
||||
|
||||
#### Example
|
||||
|
||||
```ts
|
||||
import { decode, ToonDecodeError } from '@toon-format/toon'
|
||||
|
||||
try {
|
||||
decode('a:\n\tb: 1')
|
||||
}
|
||||
catch (error) {
|
||||
if (error instanceof ToonDecodeError) {
|
||||
console.error(`Line ${error.line}:`, error.source)
|
||||
console.error(error.message)
|
||||
// Line 2: b: 1
|
||||
// Line 2: Tabs are not allowed in indentation in strict mode
|
||||
}
|
||||
else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
::: info Backwards Compatibility
|
||||
`ToonDecodeError` extends `SyntaxError`. Code written against earlier versions that catches `SyntaxError` continues to match these errors. The class adds structured fields without removing anything.
|
||||
:::
|
||||
|
||||
## Configuration Reference
|
||||
|
||||
### `EncodeOptions`
|
||||
|
||||
Configuration for [`encode()`](#encode-input-options) and [`encodeLines()`](#encodelines-input-options):
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
|--------|------|---------|-------------|
|
||||
| `indent` | `number` | `2` | Number of spaces per indentation level |
|
||||
| `delimiter` | `','` \| `'\t'` \| `'\|'` | `','` | Delimiter for array values and tabular rows |
|
||||
| `keyFolding` | `'off'` \| `'safe'` | `'off'` | Enable key folding to collapse single-key wrapper chains into dotted paths |
|
||||
| `flattenDepth` | `number` | `Infinity` | Maximum number of segments to fold when `keyFolding` is enabled (values 0-1 have no practical effect) |
|
||||
| `replacer` | `EncodeReplacer` | `undefined` | Optional hook to transform or omit values before encoding (see [Replacer Function](#replacer-function)) |
|
||||
|
||||
**Delimiter options:**
|
||||
|
||||
::: code-group
|
||||
|
||||
```ts [Comma (default)]
|
||||
encode(data, { delimiter: ',' })
|
||||
```
|
||||
|
||||
```ts [Tab]
|
||||
encode(data, { delimiter: '\t' })
|
||||
```
|
||||
|
||||
```ts [Pipe]
|
||||
encode(data, { delimiter: '|' })
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
See [Delimiter Strategies](#delimiter-strategies) for guidance on choosing delimiters.
|
||||
|
||||
### `DecodeOptions`
|
||||
|
||||
Configuration for [`decode()`](#decode-input-options) and [`decodeFromLines()`](#decodefromlines-lines-options):
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
|--------|------|---------|-------------|
|
||||
| `indent` | `number` | `2` | Expected number of spaces per indentation level |
|
||||
| `strict` | `boolean` | `true` | Enable strict validation (array counts, indentation, delimiter consistency) |
|
||||
| `expandPaths` | `'off'` \| `'safe'` | `'off'` | Enable path expansion to reconstruct dotted keys into nested objects (pairs with `keyFolding: 'safe'`) |
|
||||
|
||||
By default (`strict: true`), the decoder validates input strictly:
|
||||
|
||||
- **Invalid escape sequences**: Throws on `\x`, unterminated strings, lone-surrogate `\uXXXX`
|
||||
- **Syntax errors**: Throws on missing colons, malformed headers
|
||||
- **Array length mismatches**: Throws when declared length doesn't match actual count
|
||||
- **Header delimiter mismatch**: Throws when the bracket-declared delimiter differs from the field-list delimiter (§14.2)
|
||||
- **Indentation errors**: Throws when leading spaces aren't exact multiples of `indent`
|
||||
- **Header structure**: Throws on leading-zero or non-integer array lengths and on intervening content between bracket/fields/colon
|
||||
- **Duplicate sibling keys**: Throws when an object has two children with the same key (§14.4)
|
||||
- **Path-expansion conflicts**: When `expandPaths: 'safe'` is set, throws on overlapping dotted paths that would collide
|
||||
|
||||
All decode errors are thrown as [`ToonDecodeError`](#error-handling) instances with structured `line` and `source` fields.
|
||||
|
||||
Set `strict: false` to skip these checks. Duplicate sibling keys and path-expansion conflicts then resolve with last-write-wins in document order.
|
||||
|
||||
See [Key Folding & Path Expansion](#key-folding-path-expansion) for more details on path expansion behavior and conflict resolution.
|
||||
|
||||
### `DecodeStreamOptions`
|
||||
|
||||
Configuration for [`decodeStreamSync()`](#decodestreamsync-lines-options) and [`decodeStream()`](#decodestream-source-options):
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
|--------|------|---------|-------------|
|
||||
| `indent` | `number` | `2` | Expected number of spaces per indentation level |
|
||||
| `strict` | `boolean` | `true` | Enable strict validation (array counts, indentation, delimiter consistency) |
|
||||
|
||||
::: warning Path Expansion Not Supported
|
||||
Path expansion requires building the full value tree, which is incompatible with event streaming. Use [`decodeFromLines()`](#decodefromlines-lines-options) if you need path expansion.
|
||||
:::
|
||||
|
||||
## TypeScript Types
|
||||
|
||||
### `JsonStreamEvent`
|
||||
|
||||
Events emitted by [`decodeStreamSync()`](#decodestreamsync-lines-options) and [`decodeStream()`](#decodestream-source-options):
|
||||
|
||||
```ts
|
||||
type JsonStreamEvent
|
||||
= | { type: 'startObject' }
|
||||
| { type: 'endObject' }
|
||||
| { type: 'startArray', length: number }
|
||||
| { type: 'endArray' }
|
||||
| { type: 'key', key: string, wasQuoted?: boolean }
|
||||
| { type: 'primitive', value: JsonPrimitive }
|
||||
```
|
||||
|
||||
### Delimiters
|
||||
|
||||
```ts
|
||||
import { DEFAULT_DELIMITER, DELIMITERS } from '@toon-format/toon'
|
||||
|
||||
DEFAULT_DELIMITER // ','
|
||||
DELIMITERS // { comma: ',', tab: '\t', pipe: '|' }
|
||||
```
|
||||
|
||||
| Export | Description |
|
||||
|--------|-------------|
|
||||
| `DEFAULT_DELIMITER` | The default delimiter character (`,`) used when none is specified |
|
||||
| `DELIMITERS` | Frozen record mapping delimiter names to their characters |
|
||||
| `Delimiter` | Type union of valid delimiter characters: `',' \| '\t' \| '\|'` |
|
||||
| `DelimiterKey` | Type union of delimiter names: `'comma' \| 'tab' \| 'pipe'` |
|
||||
|
||||
### Option Types
|
||||
|
||||
| Export | Description |
|
||||
|--------|-------------|
|
||||
| `EncodeOptions` | Options accepted by [`encode()`](#encode-input-options) and [`encodeLines()`](#encodelines-input-options) |
|
||||
| `DecodeOptions` | Options accepted by [`decode()`](#decode-input-options) and [`decodeFromLines()`](#decodefromlines-lines-options) |
|
||||
| `DecodeStreamOptions` | Options accepted by [`decodeStreamSync()`](#decodestreamsync-lines-options) and [`decodeStream()`](#decodestream-source-options) |
|
||||
| `EncodeReplacer` | Signature of the [replacer function](#replacer-function) |
|
||||
| `ResolvedEncodeOptions` | `EncodeOptions` after defaults are applied (advanced) |
|
||||
| `ResolvedDecodeOptions` | `DecodeOptions` after defaults are applied (advanced) |
|
||||
|
||||
## Guides & Examples
|
||||
|
||||
### Round-Trip Compatibility
|
||||
|
||||
TOON provides lossless round-trips after normalization:
|
||||
|
||||
```ts
|
||||
import { decode, encode } from '@toon-format/toon'
|
||||
|
||||
const original = {
|
||||
users: [
|
||||
{ id: 1, name: 'Alice', role: 'admin' },
|
||||
{ id: 2, name: 'Bob', role: 'user' }
|
||||
]
|
||||
}
|
||||
|
||||
const toon = encode(original)
|
||||
const restored = decode(toon)
|
||||
|
||||
console.log(JSON.stringify(original) === JSON.stringify(restored))
|
||||
// true
|
||||
```
|
||||
|
||||
**With Key Folding:**
|
||||
|
||||
```ts
|
||||
import { decode, encode } from '@toon-format/toon'
|
||||
|
||||
const original = { data: { metadata: { items: ['a', 'b'] } } }
|
||||
|
||||
// Encode with folding
|
||||
const toon = encode(original, { keyFolding: 'safe' })
|
||||
// → "data.metadata.items[2]: a,b"
|
||||
|
||||
// Decode with expansion
|
||||
const restored = decode(toon, { expandPaths: 'safe' })
|
||||
// → { data: { metadata: { items: ['a', 'b'] } } }
|
||||
|
||||
console.log(JSON.stringify(original) === JSON.stringify(restored))
|
||||
// true
|
||||
```
|
||||
|
||||
### Key Folding & Path Expansion
|
||||
|
||||
**Key Folding** (`keyFolding: 'safe'`) collapses single-key wrapper chains during encoding:
|
||||
|
||||
```ts
|
||||
import { encode } from '@toon-format/toon'
|
||||
|
||||
const data = { data: { metadata: { items: ['a', 'b'] } } }
|
||||
|
||||
// Without folding
|
||||
encode(data)
|
||||
// data:
|
||||
// metadata:
|
||||
// items[2]: a,b
|
||||
|
||||
// With folding
|
||||
encode(data, { keyFolding: 'safe' })
|
||||
// data.metadata.items[2]: a,b
|
||||
```
|
||||
|
||||
**Path Expansion** (`expandPaths: 'safe'`) reverses this during decoding:
|
||||
|
||||
```ts
|
||||
import { decode } from '@toon-format/toon'
|
||||
|
||||
const toon = 'data.metadata.items[2]: a,b'
|
||||
|
||||
const data = decode(toon, { expandPaths: 'safe' })
|
||||
console.log(data)
|
||||
// { data: { metadata: { items: ['a', 'b'] } } }
|
||||
```
|
||||
|
||||
**Expansion Conflict Resolution:**
|
||||
|
||||
When multiple expanded keys construct overlapping paths, the decoder merges them recursively:
|
||||
- **Object + Object**: Deep merge recursively
|
||||
- **Object + Non-object** (array or primitive): Conflict
|
||||
- With `strict: true` (default): Error
|
||||
- With `strict: false`: Last-write-wins (LWW)
|
||||
|
||||
Duplicate sibling keys (independent of `expandPaths`) follow the same policy: strict mode throws, lenient mode keeps the last value seen.
|
||||
|
||||
### Delimiter Strategies
|
||||
|
||||
Tab delimiters (`\t`) often tokenize more efficiently than commas. Tabs are single characters that rarely appear in natural text, which reduces the need for quote-escaping and leads to smaller token counts in large datasets.
|
||||
|
||||
Example:
|
||||
|
||||
```yaml
|
||||
items[2 ]{sku name qty price}:
|
||||
A1 Widget 2 9.99
|
||||
B2 Gadget 1 14.5
|
||||
```
|
||||
|
||||
For maximum token savings on large tabular data, combine tab delimiters with key folding:
|
||||
|
||||
```ts
|
||||
encode(data, { delimiter: '\t', keyFolding: 'safe' })
|
||||
```
|
||||
|
||||
**Choosing a Delimiter:**
|
||||
|
||||
- **Comma (`,`)**: Default, widely understood, good for simple tabular data.
|
||||
- **Tab (`\t`)**: Best for LLM token efficiency, excellent for large datasets.
|
||||
- **Pipe (`|`)**: Alternative when commas appear frequently in data.
|
||||
@@ -0,0 +1,509 @@
|
||||
---
|
||||
description: Mathematical model of TOON's byte-level overhead vs JSON across structure families, with formulas and worked examples.
|
||||
---
|
||||
|
||||
# TOON vs JSON: Byte-Level Efficiency Model
|
||||
|
||||
A mathematical analysis of TOON's byte efficiency compared to JSON across different data structures.
|
||||
|
||||
::: info Scope of This Document
|
||||
This page presents a theoretical, character-based comparison between TOON and JSON. For practical benchmarks and token counts, see [Benchmarks](/guide/benchmarks). It is an **advanced, non-normative** reference: it explains TOON's design from a mathematical angle but does not change the TOON specification.
|
||||
:::
|
||||
|
||||
## Overview
|
||||
|
||||
Standard JSON introduces structural verbosity that inflates token usage and inference cost. This page formalises a byte-level comparison between TOON and JSON to evaluate whether TOON achieves quantifiable efficiency gains by removing structural redundancy.
|
||||
|
||||
Under the assumptions described below (compact JSON, canonical TOON, ASCII keys and punctuation, shallow to moderate nesting, and mostly unquoted TOON strings), TOON's **structural overhead is lower than compact JSON** for the structure families analyzed here, except arrays of arrays.
|
||||
|
||||
### Key Findings
|
||||
|
||||
- **Tabular arrays** represent TOON's optimal use case, with efficiency gains scaling linearly with both row count and field count.
|
||||
- **Simple objects and primitive arrays** show consistent byte reduction, with savings proportional to the number of fields or elements.
|
||||
- **Nested objects** benefit from reduced overhead, though efficiency decreases with depth due to indentation costs; at sufficient depth, compact JSON can become smaller.
|
||||
- **Arrays of arrays** are the only structure where TOON is less efficient than JSON in this analysis, due to TOON's explicit list markers and inner array headers.
|
||||
|
||||
## Methodology
|
||||
|
||||
We define recursive byte-length functions $L_{\text{json}}$ and $L_{\text{toon}}$ for both formats, then derive the efficiency delta:
|
||||
|
||||
$$
|
||||
\Delta = L_{\text{json}}(\Omega) - L_{\text{toon}}(\Omega)
|
||||
$$
|
||||
|
||||
Where $\Omega$ represents the data structure under comparison. If $\Delta > 0$, TOON uses fewer bytes than JSON for that structure.
|
||||
|
||||
::: info Scope & Assumptions
|
||||
- **Compact JSON**: JSON is assumed to be compact (no spaces or newlines outside strings). Byte counts are computed on this compact form.
|
||||
- **Canonical TOON**: TOON is assumed to follow canonical formatting (indent = 2 spaces, exactly one space after `:`, no spaces after commas in arrays/field lists, no trailing spaces).
|
||||
- **Keys and strings**: All keys are "simple" ASCII identifier-style keys that:
|
||||
- must be quoted in JSON, and
|
||||
- can be left unquoted in TOON (no characters that would force quoting).
|
||||
Many examples assume values are numbers, booleans, null, or TOON-safe strings that can be unquoted in TOON but must be quoted in JSON.
|
||||
- **Numbers**: For this analysis only, both formats are assumed to use the same canonical decimal representation. JSON could use exponent forms; we ignore that here to isolate structural differences.
|
||||
- **ASCII/UTF-8**: Keys and structural tokens are assumed ASCII, so byte length equals character count ($|x|_{\text{utf8}} = |x|_{\text{char}}$). Non-ASCII content affects both formats similarly and does not change the structural conclusions.
|
||||
- **Nesting depth**: Closed-form expressions are given for flat structures and a single level of nesting. Each additional nesting level in TOON adds 2 bytes of indentation per nested line. At sufficient depth, the braces of compact JSON can win over TOON's indentation (as seen in [When Not to Use TOON](/guide/getting-started#when-not-to-use-toon)).
|
||||
- **Byte vs token count**: Modern LLM tokenizers operate over UTF-8 bytes, so byte length is a good upper bound and first-order proxy for token count, even though the mapping is not exactly linear.
|
||||
:::
|
||||
|
||||
Think of this as a simplified structural model: we strip away real-world noise and ask, "if you only count structural characters, how do JSON and TOON compare?"
|
||||
|
||||
## Formal Notation
|
||||
|
||||
### Data Model
|
||||
|
||||
Let $\omega$ be a primitive value such that $\omega \in \{\text{string, number, boolean, null}\}$.
|
||||
|
||||
Let $\mathcal{O}$ be an object composed of $n$ key-value pairs:
|
||||
|
||||
$$
|
||||
\mathcal{O} = \{(k_1, v_1), (k_2, v_2), \dots, (k_n, v_n)\}
|
||||
$$
|
||||
|
||||
Let $\mathcal{A}$ be an array composed of $n$ elements:
|
||||
|
||||
$$
|
||||
\mathcal{A} = \{v_1, v_2, \dots, v_n\}
|
||||
$$
|
||||
|
||||
Where:
|
||||
- $k_i$ is a key (string)
|
||||
- $v_i$ can be a primitive value $\omega$, an object $\mathcal{O}$, or an array $\mathcal{A}$
|
||||
|
||||
Therefore: $v_i \in \{\omega, \mathcal{O}, \mathcal{A}\}$
|
||||
|
||||
### String Length
|
||||
|
||||
Let $\mathcal{S}$ be the set of valid Unicode strings. For any string $x \in \mathcal{S}$, we denote $|x|_{\text{utf8}}$ as the byte-length of $x$ under UTF-8 encoding.
|
||||
|
||||
### Integer Length
|
||||
|
||||
Let $n \in \mathbb{Z}_{\ge 0}$ be a non-negative integer. The number of bytes required to represent $n$ in decimal format is:
|
||||
|
||||
$$
|
||||
L_{\text{num}}(n) = \begin{cases}
|
||||
1 & \text{if } n = 0 \\
|
||||
\lfloor \log_{10}(|n|) \rfloor + 1 & \text{if } n > 0
|
||||
\end{cases}
|
||||
$$
|
||||
|
||||
## JSON Size Functions
|
||||
|
||||
For a flat object of $n$ keys:
|
||||
|
||||
$$
|
||||
L_{\text{json}}(\mathcal{O}) = \underbrace{2}_{\{\}} + \sum_{i=1}^{n} (L_{\text{str}}(k_i) + \underbrace{1}_{:} + L_{\text{json}}(v_i)) + \underbrace{(n-1)}_{\text{commas}}
|
||||
$$
|
||||
|
||||
Where $L_{\text{str}}(k)$ is the length of the key including its mandatory quotes:
|
||||
|
||||
$$
|
||||
L_{\text{str}}(k) = |k|_{\text{utf8}} + \underbrace{2}_{\text{quotes}}
|
||||
$$
|
||||
|
||||
### Primitive Values in JSON
|
||||
|
||||
When $v_i$ is a primitive data type $\omega$:
|
||||
|
||||
| Type | Formula |
|
||||
|------|---------|
|
||||
| String | $L_{\text{str}}(v_i) = \lvert v_i\rvert_{\text{utf8}} + 2$ |
|
||||
| Number | $L_{\text{num}}(v_i) = \lvert v_i\rvert_{\text{utf8}}$ |
|
||||
| Boolean | $L_{\text{bool}}(v_i) = \lvert v_i\rvert_{\text{utf8}}$ |
|
||||
| Null | $L_{\text{null}}(v_i) = \lvert v_i\rvert_{\text{utf8}}$ |
|
||||
|
||||
### Arrays in JSON
|
||||
|
||||
When $v_i$ is an array $\mathcal{A}$:
|
||||
|
||||
$$
|
||||
L_{\text{json}}(\mathcal{A}) = \underbrace{2}_{\text{[]}} + \sum_{i=1}^{n} L_{\text{json}}(v_i) + \underbrace{(n-1)}_{\text{commas}}
|
||||
$$
|
||||
|
||||
## TOON Size Functions
|
||||
|
||||
For a flat object of $n$ keys:
|
||||
|
||||
$$
|
||||
L_{\text{toon}}(\mathcal{O}) = \sum_{i=1}^{n} (L_{\text{str}}(k_i) + \underbrace{1}_{:} + \underbrace{1}_{\text{space}} + L_{\text{toon}}(v_i)) + \underbrace{(n-1)}_{\text{newlines}}
|
||||
$$
|
||||
|
||||
Where $L_{\text{str}}(k)$ is the length of the key (no quotes required for simple keys):
|
||||
|
||||
$$
|
||||
L_{\text{str}}(k) = |k|_{\text{utf8}}
|
||||
$$
|
||||
|
||||
### Primitive Values in TOON
|
||||
|
||||
When $v_i$ is a primitive data type $\omega$:
|
||||
|
||||
| Type | Formula |
|
||||
|------|---------|
|
||||
| String (normal) | $L_{\text{str}}(v_i) = \lvert v_i\rvert_{\text{utf8}}$ |
|
||||
| String (looks like number/boolean) | $L_{\text{str}}(v_i) = \lvert v_i\rvert_{\text{utf8}} + 2$ |
|
||||
| Number | $L_{\text{num}}(v_i) = \lvert v_i\rvert_{\text{utf8}}$ |
|
||||
| Boolean | $L_{\text{bool}}(v_i) = \lvert v_i\rvert_{\text{utf8}}$ |
|
||||
| Null | $L_{\text{null}}(v_i) = \lvert v_i\rvert_{\text{utf8}}$ |
|
||||
|
||||
### Simple Arrays in TOON
|
||||
|
||||
Here $L_{\text{toon}}(\mathcal{A})$ refers to the length of the whole field line `key[N]: ...`, not just the array value.
|
||||
|
||||
When $v_i$ is a simple array $\mathcal{A}$:
|
||||
|
||||
$$
|
||||
L_{\text{toon}}(\mathcal{A}) = L_{\text{str}}(k_i) + \underbrace{1}_{\text{[}} + L_{\text{num}}(n) + \underbrace{1}_{\text{]}} + \underbrace{1}_{:} + \underbrace{1}_{\text{space}} + \sum_{i=1}^{n} L_{\text{toon}}(v_i) + \underbrace{(n-1)}_{\text{commas}}
|
||||
$$
|
||||
|
||||
### Tabular Arrays in TOON
|
||||
|
||||
When $v_i$ is an array of objects with $m$ fields:
|
||||
|
||||
$$
|
||||
\begin{split}
|
||||
L_{\text{toon}}(\mathcal{A}') = L_{\text{str}}(k_i) + \underbrace{1}_{\text{[}} + L_{\text{num}}(n) + \underbrace{1}_{\text{]}} + \underbrace{1}_{\{} + \\
|
||||
\sum_{i=1}^{m} L_{\text{str}}(k_i) + \underbrace{(m-1)}_{\text{commas}} + \underbrace{1}_{\}} + \underbrace{1}_{:} + \\
|
||||
\underbrace{2n}_{\text{indents}} + \sum_{i=1}^{n}\sum_{j=1}^{m} L_{\text{toon}}(v_{ij}) + \underbrace{(m-1)n}_{\text{commas}} + \underbrace{n}_{\text{newlines}}
|
||||
\end{split}
|
||||
$$
|
||||
|
||||
*Note: The term $2n$ assumes an indentation size of 2 spaces.*
|
||||
|
||||
## Efficiency Analysis by Structure
|
||||
|
||||
Each subsection below focuses on a particular structure family, states the resulting formula, and shows a small example. Intuitively, TOON tends to win when it can:
|
||||
|
||||
- avoid repeating keys (tabular arrays),
|
||||
- avoid quoting keys and many values,
|
||||
- and replace braces with indentation,
|
||||
|
||||
and tends to lose when it pays a fixed overhead per element (arrays of arrays) or deep indentation (heavily nested configs).
|
||||
|
||||
### Simple Objects
|
||||
|
||||
Flat objects with primitive string values are the easiest win: JSON pays for braces and quoted keys and strings, while TOON drops braces at the root, omits quotes on simple keys, and uses one line per field.
|
||||
|
||||
For objects with only string primitives:
|
||||
|
||||
$$
|
||||
\Delta_{\text{obj}} = 2 + n + \sum_{i=1}^{n}(L_{\text{json}}(v_i)) - \sum_{i=1}^{n}(L_{\text{toon}}(v_i))
|
||||
$$
|
||||
|
||||
If all values are strings that can be unquoted in TOON, this simplifies to:
|
||||
|
||||
$$
|
||||
f(n) = 2 + 3n
|
||||
$$
|
||||
|
||||
**Example:** For 1,000,000 objects, TOON saves **3,000,002 bytes ≈ 2.86 MB**.
|
||||
|
||||
#### Empirical Validation
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (21 bytes)]
|
||||
{ "id": 1, "name": "Ada" }
|
||||
```
|
||||
|
||||
```yaml [TOON (15 bytes)]
|
||||
id: 1
|
||||
name: Ada
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
$$
|
||||
\Delta_{\text{obj}} = 2 + \underbrace{2}_{n} + \underbrace{6}_{\sum L_{\text{json}}(v_i)} - \underbrace{4}_{\sum L_{\text{toon}}(v_i)} = 6
|
||||
$$
|
||||
|
||||
### Nested Objects
|
||||
|
||||
Adding a wrapper object (one extra level of nesting) introduces extra braces for JSON and extra indentation and newlines for TOON. For a single level of nesting with primitive values, TOON still comes out ahead, but the net advantage is smaller.
|
||||
|
||||
For a single level of nesting with primitives:
|
||||
|
||||
$$
|
||||
f(n) = 5 + n
|
||||
$$
|
||||
|
||||
**Example:** For 1,000,000 nested objects (depth 1), TOON saves **1,000,005 bytes ≈ 0.95 MB**.
|
||||
|
||||
::: warning Caveat
|
||||
This formula is for a single nesting level. Each additional nesting level adds 2 spaces of indentation per nested line; at sufficient depth, compact JSON can become smaller, especially when tabular opportunities disappear (see [When Not to Use TOON](/guide/getting-started#when-not-to-use-toon) and the "Deeply nested configuration" dataset in [Benchmarks](/guide/benchmarks)).
|
||||
:::
|
||||
|
||||
#### Empirical Validation
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (30 bytes)]
|
||||
{ "user": { "id": 1, "name": "Ada" } }
|
||||
```
|
||||
|
||||
```yaml [TOON (25 bytes)]
|
||||
user:
|
||||
id: 1
|
||||
name: Ada
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
$$
|
||||
\Delta_{\text{nested}} = 5
|
||||
$$
|
||||
|
||||
### Primitive Arrays
|
||||
|
||||
For arrays of string primitives, JSON writes `["foo","bar","baz"]`, quoting every string and using `[]` for the array. TOON writes `key[N]: foo,bar,baz`, paying once for the length marker but omitting most quotes.
|
||||
|
||||
For arrays of $n$ string primitives:
|
||||
|
||||
$$
|
||||
\Delta_{\text{arr}} = 3 - L_{\text{num}}(n) + \sum_{i=1}^{n}(L_{\text{json}}(v_i)) - \sum_{i=1}^{n}(L_{\text{toon}}(v_i))
|
||||
$$
|
||||
|
||||
With string values that can be unquoted in TOON, this simplifies to:
|
||||
|
||||
$$
|
||||
f(n) = 2 + 2n - \lfloor \log_{10}(|n|) \rfloor
|
||||
$$
|
||||
|
||||
**Example:** For 1,000,000 elements, TOON saves **1,999,996 bytes ≈ 1.91 MB**.
|
||||
|
||||
#### Empirical Validation
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (28 bytes)]
|
||||
{ "tags": ["foo", "bar", "baz"] }
|
||||
```
|
||||
|
||||
```yaml [TOON (20 bytes)]
|
||||
tags[3]: foo,bar,baz
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
$$
|
||||
\Delta_{\text{arr}} = 3 - \underbrace{1}_{L_{\text{num}}(3)} + \underbrace{15}_{\sum L_{\text{json}}} - \underbrace{9}_{\sum L_{\text{toon}}} = 8
|
||||
$$
|
||||
|
||||
### Root Arrays
|
||||
|
||||
At the root, JSON writes `["x","y","z"]`; TOON writes `[3]: x,y,z`. There is no object key cost, so the advantage mainly comes from not quoting TOON-safe strings and from replacing `[]` with `[N]:`.
|
||||
|
||||
For root-level arrays of $n$ string primitives:
|
||||
|
||||
$$
|
||||
f(n) = -3 + 2n - \lfloor \log_{10}(|n|) \rfloor
|
||||
$$
|
||||
|
||||
**Example:** For 1,000,000 elements, TOON saves **1,999,991 bytes ≈ 1.91 MB**.
|
||||
|
||||
#### Empirical Validation
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (13 bytes)]
|
||||
["x", "y", "z"]
|
||||
```
|
||||
|
||||
```yaml [TOON (10 bytes)]
|
||||
[3]: x,y,z
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
$$
|
||||
\Delta_{\text{root}} = \underbrace{9}_{\sum L_{\text{json}}} - 2 - \underbrace{1}_{L_{\text{num}}(3)} - \underbrace{3}_{\sum L_{\text{toon}}} = 3
|
||||
$$
|
||||
|
||||
### Tabular Arrays
|
||||
|
||||
Uniform arrays of objects are TOON's sweet spot. JSON repeats every key for every row, while TOON declares the length and column names once (`key[N]{id,qty,...}:`) and streams rows as bare values.
|
||||
|
||||
For arrays of objects with $n$ rows and $m$ fields, assuming numeric values and $|k| = 3$:
|
||||
|
||||
$$
|
||||
f(n) = 1 + nm(3 + |k|) - m(1 + |k|) - \lfloor \log_{10}(|n|) \rfloor
|
||||
$$
|
||||
|
||||
**Example:** For 1,000,000 rows with 2 fields and 3-character field names, TOON saves **11,999,987 bytes ≈ 11.44 MB**.
|
||||
|
||||
This is where TOON's design (declare fields once, stream rows) pays off most strongly: savings grow linearly with both row count and field count.
|
||||
|
||||
#### Empirical Validation
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (45 bytes)]
|
||||
{ "items": [{ "id": 1, "qty": 5 }, { "id": 2, "qty": 3 }] }
|
||||
```
|
||||
|
||||
```yaml [TOON (29 bytes)]
|
||||
items[2]{id,qty}:
|
||||
1,5
|
||||
2,3
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
$$
|
||||
\Delta_{\text{tab}} = 2 + \underbrace{4}_{nm} - \underbrace{2}_{m} + \underbrace{22}_{\Sigma L_{\text{json}}} - \underbrace{1}_{L_{\text{num}}(n)} - \underbrace{5}_{\Sigma L_{\text{toon}}(k)} - \underbrace{4}_{\Sigma L_{\text{toon}}(v)} = 16
|
||||
$$
|
||||
|
||||
### Arrays of Arrays
|
||||
|
||||
Arrays of arrays of primitives are where TOON structurally loses: each inner array becomes a list item with its own header, so TOON pays a fixed overhead per inner array (`"- "` plus `"[m]: "`), while JSON just uses commas.
|
||||
|
||||
::: info Practical Note
|
||||
For arrays of arrays of primitives, this model predicts that JSON is more byte-efficient than TOON, because TOON pays ~6 extra bytes per inner array (2 for `"- "`, 4 for `"[m]: "`), plus the length marker.
|
||||
:::
|
||||
|
||||
For arrays of arrays with $n$ outer elements and $m$ inner elements:
|
||||
|
||||
$$
|
||||
\begin{split}
|
||||
\Delta_{\text{arrarr}} = 2 - 6n - \sum_{i=1}^{n}\sum_{j=1}^{m} L_{\text{num}}(m) + \\
|
||||
\sum_{i=1}^{n}\sum_{j=1}^{m} L_{\text{json}}(v_{ij}) - \sum_{i=1}^{n}\sum_{j=1}^{m} L_{\text{toon}}(v_{ij})
|
||||
\end{split}
|
||||
$$
|
||||
|
||||
With string primitives and $m = 2$:
|
||||
|
||||
$$
|
||||
f(n) = 2 - 6n - \sum_{i=1}^{n}\sum_{j=1}^{m} (\lfloor \log_{10}(|m|) \rfloor + 1) + 2nm
|
||||
$$
|
||||
|
||||
**Example:** For 1,000,000 arrays with $m = 2$, TOON **wastes 2,999,998 bytes ≈ 2.86 MB** relative to JSON under this model.
|
||||
|
||||
#### Empirical Validation
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (23 bytes)]
|
||||
{ "pairs": [[1, 2], [3, 4]] }
|
||||
```
|
||||
|
||||
```yaml [TOON (35 bytes)]
|
||||
pairs[2]:
|
||||
- [2]: 1,2
|
||||
- [2]: 3,4
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
$$
|
||||
\Delta_{\text{arrarr}} = 2 - \underbrace{12}_{6n} - \underbrace{2}_{\sum L_{\text{num}}(m)} + \underbrace{4}_{\sum L_{\text{json}}} - \underbrace{4}_{\sum L_{\text{toon}}} = -12
|
||||
$$
|
||||
|
||||
### Strings That Look Like Literals
|
||||
|
||||
Strings that look like numbers or booleans (e.g. `"123"`, `"true"`) must be quoted in both JSON and TOON, slightly reducing TOON's advantage because it no longer saves quotes on those values.
|
||||
|
||||
For objects containing such strings:
|
||||
|
||||
$$
|
||||
\Delta_{\text{strlit}} = 2 + n
|
||||
$$
|
||||
|
||||
**Example:** For 1,000,000 objects, TOON saves **2,000,002 bytes ≈ 1.91 MB**.
|
||||
|
||||
#### Empirical Validation
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON (34 bytes)]
|
||||
{ "version": "123", "enabled": "true" }
|
||||
```
|
||||
|
||||
```yaml [TOON (30 bytes)]
|
||||
version: "123"
|
||||
enabled: "true"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
$$
|
||||
\Delta_{\text{str}} = 2 + \underbrace{2}_{n} = 4
|
||||
$$
|
||||
|
||||
### Empty Structures
|
||||
|
||||
Empty containers reveal structural differences even at minimal sizes.
|
||||
|
||||
**Empty Object:**
|
||||
|
||||
$$
|
||||
\Delta_{\text{EmptyObject}} = 2
|
||||
$$
|
||||
|
||||
JSON requires `{}` (2 bytes), whereas a completely empty root object in TOON is represented as an empty document (0 bytes).
|
||||
|
||||
**Empty Array (field):**
|
||||
|
||||
$$
|
||||
\Delta_{\text{EmptyArray}} = 3
|
||||
$$
|
||||
|
||||
For a field named `key`, JSON uses `{"key":[]}` in compact form, while TOON uses:
|
||||
|
||||
```yaml
|
||||
key: []
|
||||
```
|
||||
|
||||
Under this model, that yields a constant 3-byte advantage for TOON. The legacy `key[0]:` form remains decodable for backward compatibility.
|
||||
|
||||
## Summary Table
|
||||
|
||||
The table below summarizes the formulas and which side wins under the modeling assumptions.
|
||||
|
||||
| Structure | Efficiency Formula | TOON Advantage? |
|
||||
|-----------|-------------------|-----------------|
|
||||
| Simple Objects | $f(n) = 2 + 3n$ | ✅ Yes |
|
||||
| Nested Objects (1 level) | $f(n) = 5 + n$ | ✅ Yes (shrinks with depth) |
|
||||
| Primitive Arrays | $f(n) = 2 + 2n - \lfloor \log_{10}(n) \rfloor$ | ✅ Yes |
|
||||
| Root Arrays | $f(n) = -3 + 2n - \lfloor \log_{10}(n) \rfloor$ | ✅ Yes |
|
||||
| Tabular Arrays | $f(n) = 1 + nm(3+\lvert k\rvert) - m(1+\lvert k\rvert) - \lfloor \log_{10}(n) \rfloor$ | ✅ **Best case** |
|
||||
| Arrays of Arrays | $f(n) = 2 - 6n + 2nm - \text{overhead}$ | ❌ JSON wins here |
|
||||
| String Literals | $f(n) = 2 + n$ | ✅ Yes (smaller gain) |
|
||||
| Empty Structures | $\Delta = 2$ or $3$ | ✅ Yes |
|
||||
|
||||
In short:
|
||||
|
||||
- TOON's gains are **linear in the number of fields** for flat objects.
|
||||
- For arrays, gains grow **linearly in the number of elements**, and for tabular arrays **linearly in both rows and fields**.
|
||||
- Arrays of arrays are the main structural case where JSON is smaller.
|
||||
- Deep nesting and heavy quoting can erode or reverse these advantages in real data.
|
||||
|
||||
## Conclusion
|
||||
|
||||
This simplified theoretical model supports TOON's design goal: structurally, it reduces overhead compared to compact JSON in many common patterns by:
|
||||
|
||||
- avoiding repeated keys in tabular arrays,
|
||||
- omitting quotes on many keys and values,
|
||||
- and replacing braces with indentation at shallow depths.
|
||||
|
||||
For the structure families examined here and under the stated assumptions, the structural overhead of TOON is lower than that of compact JSON except for arrays of arrays. Since UTF-8 byte length is a reasonable first-order proxy for tokens, these structural savings usually translate into lower token counts in those patterns.
|
||||
|
||||
At the same time, this is deliberately a simplified model. In real datasets, additional factors – deeper or irregular nesting, heavily quoted strings, exponent notation in JSON, and tokenizer idiosyncrasies – can reduce or even reverse these gains. Our [Benchmarks](/guide/benchmarks) and [When Not to Use TOON](/guide/getting-started#when-not-to-use-toon) show that compact JSON can be more efficient for deeply nested or low-tabularity data. Use this page as intuition for *why* TOON behaves the way it does, not as a universal guarantee.
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [Benchmarks](/guide/benchmarks) – Empirical token count and accuracy comparisons across formats
|
||||
- [Specification](/reference/spec) – Formal TOON specification
|
||||
|
||||
## References
|
||||
|
||||
This analysis is based on:
|
||||
|
||||
- **Original Research**: [TOON vs. JSON: A Mathematical Evaluation of Byte Efficiency in Structured Data](https://www.researchgate.net/publication/397903673_TOON_vs_JSON_A_Mathematical_Evaluation_of_Byte_Efficiency_in_Structured_Data)
|
||||
- **TOON Specification**: [toon-format/spec](https://github.com/toon-format/spec)
|
||||
- **JSON Specification**: [RFC 8259](https://datatracker.ietf.org/doc/html/rfc8259), [ECMA-404](https://www.ecma-international.org/publications-and-standards/standards/ecma-404/)
|
||||
|
||||
---
|
||||
|
||||
This page was contributed by Mateo Lafalce ([@mateolafalce](https://github.com/mateolafalce)).
|
||||
|
||||
*Have questions or found an error in the formalization? Open an issue on [GitHub](https://github.com/toon-format/spec) or contribute improvements to this analysis.*
|
||||
@@ -0,0 +1,175 @@
|
||||
---
|
||||
description: Guided tour of the TOON specification – sections, conformance checklists, media type, and versioning.
|
||||
---
|
||||
|
||||
# Specification
|
||||
|
||||
The [TOON specification](https://github.com/toon-format/spec) is the authoritative reference for implementing encoders, decoders, and validators. It defines the concrete syntax, normative encoding/decoding behavior, and strict-mode validation rules.
|
||||
|
||||
You don't need this page to *use* TOON. It's mainly for implementers and contributors. If you're looking to learn how to use TOON, start with the [Getting Started](/guide/getting-started) guide instead.
|
||||
|
||||
> [!NOTE]
|
||||
> The TOON specification is stable, but also an idea in progress. Nothing's set in stone – help shape where it goes by contributing to it or sharing feedback.
|
||||
|
||||
## Current Version
|
||||
|
||||
**Spec v{{ $spec.version }}** (2026-05-20) is the current published Working Draft. It is stable for implementation but not yet finalized; see "Status of This Document" in the spec for details.
|
||||
|
||||
## Media Type & File Extension
|
||||
|
||||
The spec defines a provisional media type and file extension in [§17](https://github.com/toon-format/spec/blob/main/SPEC.md#17-iana-considerations):
|
||||
|
||||
- **Media type:** `text/toon` (provisional, not yet IANA‑registered; UTF‑8 only)
|
||||
- **File extension:** `.toon`
|
||||
|
||||
TOON documents are always UTF‑8 with LF (`\n`) line endings; the optional `charset` parameter, when present, is `utf-8`.
|
||||
|
||||
## Guided Tour of the Spec
|
||||
|
||||
### Core Concepts
|
||||
|
||||
[§1 Terminology and Conventions](https://github.com/toon-format/spec/blob/main/SPEC.md#1-terminology-and-conventions):
|
||||
Defines key terms like "indentation level", "active delimiter", "strict mode", and RFC2119 keywords (MUST, SHOULD, MAY).
|
||||
|
||||
[§2 Data Model](https://github.com/toon-format/spec/blob/main/SPEC.md#2-data-model):
|
||||
Specifies the JSON data model (objects, arrays, primitives), array/object ordering requirements, and canonical number formatting (canonical decimal for values in `[1e-6, 1e21)` or zero; exponent form permitted outside).
|
||||
|
||||
[§3 Encoding Normalization](https://github.com/toon-format/spec/blob/main/SPEC.md#3-encoding-normalization-reference-encoder):
|
||||
Defines how non-JSON types (Date, BigInt, NaN, Infinity, undefined, etc.) are normalized before encoding. Required reading for encoder implementers.
|
||||
|
||||
[§4 Decoding Interpretation](https://github.com/toon-format/spec/blob/main/SPEC.md#4-decoding-interpretation-reference-decoder):
|
||||
Specifies how decoders map text tokens to host values (quoted strings, unquoted primitives, numeric parsing with leading-zero handling). Decoders default to strict mode (`strict = true`) in the reference implementation; strict-mode errors are enumerated in §14.
|
||||
|
||||
### Syntax Rules
|
||||
|
||||
[§5 Concrete Syntax and Root Form](https://github.com/toon-format/spec/blob/main/SPEC.md#5-concrete-syntax-and-root-form):
|
||||
Defines TOON's line-oriented, indentation-based notation and how to determine whether the root is an object, array, or primitive.
|
||||
|
||||
[§6 Header Syntax](https://github.com/toon-format/spec/blob/main/SPEC.md#6-header-syntax-normative):
|
||||
Normative ABNF grammar for array headers: `key[N<delim?>]{fields}:`. Specifies bracket segments, delimiter symbols, and field lists.
|
||||
|
||||
[§7 Strings and Keys](https://github.com/toon-format/spec/blob/main/SPEC.md#7-strings-and-keys):
|
||||
Complete quoting rules (when strings MUST be quoted), escape sequences (only `\\`, `\"`, `\n`, `\r`, `\t`, and `\uXXXX` for other U+0000–U+001F controls are valid), and key encoding requirements.
|
||||
|
||||
[§8 Objects](https://github.com/toon-format/spec/blob/main/SPEC.md#8-objects):
|
||||
Object field encoding (key: value), nesting rules, key order preservation, and empty object handling.
|
||||
|
||||
[§9 Arrays](https://github.com/toon-format/spec/blob/main/SPEC.md#9-arrays):
|
||||
Covers all array forms: primitive (inline), arrays of objects (tabular), mixed/non-uniform (list), and arrays of arrays. Includes tabular detection requirements.
|
||||
|
||||
[§10 Objects as List Items](https://github.com/toon-format/spec/blob/main/SPEC.md#10-objects-as-list-items):
|
||||
Indentation rules for objects appearing in list items (first field on the hyphen line), including the canonical pattern when the first field is a tabular array (header on the hyphen line, rows at depth +2, sibling fields at depth +1).
|
||||
|
||||
[§11 Delimiters](https://github.com/toon-format/spec/blob/main/SPEC.md#11-delimiters):
|
||||
Delimiter scoping (document vs active), delimiter-aware quoting, and parsing rules for comma/tab/pipe delimiters.
|
||||
|
||||
[§12 Indentation and Whitespace](https://github.com/toon-format/spec/blob/main/SPEC.md#12-indentation-and-whitespace):
|
||||
Encoding requirements (consistent spaces, no tabs in indentation, no trailing spaces/newlines) and decoding rules (strict vs non-strict indentation handling).
|
||||
|
||||
### Conformance and Validation
|
||||
|
||||
[§13 Conformance and Options](https://github.com/toon-format/spec/blob/main/SPEC.md#13-conformance-and-options):
|
||||
Defines conformance classes (encoder, decoder, validator), standardized options, and conformance checklists.
|
||||
|
||||
[§13.4 Key Folding and Path Expansion](https://github.com/toon-format/spec/blob/main/SPEC.md#134-key-folding-and-path-expansion):
|
||||
Optional encoder feature (key folding) and decoder feature (path expansion) for collapsing/expanding dotted paths, with deep-merge semantics and strict/non-strict conflict resolution.
|
||||
|
||||
[§14 Strict Mode Errors and Diagnostics](https://github.com/toon-format/spec/blob/main/SPEC.md#14-strict-mode-errors-and-diagnostics-authoritative-checklist):
|
||||
**Authoritative checklist** of all strict-mode errors: array count and width mismatches (§14.1), syntax and structural errors (§14.2), path expansion conflicts (§14.3), and duplicate sibling keys (§14.4).
|
||||
|
||||
### Implementation Guidance
|
||||
|
||||
[§15 Security Considerations](https://github.com/toon-format/spec/blob/main/SPEC.md#15-security-considerations):
|
||||
Injection risks, quoting rules, and strict-mode checks relevant to security.
|
||||
|
||||
[§16 Internationalization](https://github.com/toon-format/spec/blob/main/SPEC.md#16-internationalization):
|
||||
Unicode handling and locale-independent number formatting.
|
||||
|
||||
[§17 IANA Considerations](https://github.com/toon-format/spec/blob/main/SPEC.md#17-iana-considerations):
|
||||
Media type registration plans and provisional status.
|
||||
|
||||
[§18 Versioning and Extensibility](https://github.com/toon-format/spec/blob/main/SPEC.md#18-versioning-and-extensibility):
|
||||
How the spec evolves: major vs minor bumps and the extensibility policy.
|
||||
|
||||
[§19 Intellectual Property Considerations](https://github.com/toon-format/spec/blob/main/SPEC.md#19-intellectual-property-considerations):
|
||||
Licensing and IP terms for the specification.
|
||||
|
||||
[Appendix F: Host Type Normalization Examples](https://github.com/toon-format/spec/blob/main/SPEC.md#appendix-f-host-type-normalization-examples-informative):
|
||||
Non-normative guidance for Go, JavaScript, Python, Rust, and Java implementations on normalizing language-specific types.
|
||||
|
||||
[Appendix C: Test Suite and Compliance](https://github.com/toon-format/spec/blob/main/SPEC.md#appendix-c-test-suite-and-compliance-informative):
|
||||
Reference test suite at [github.com/toon-format/spec/tree/main/tests](https://github.com/toon-format/spec/tree/main/tests) for validating implementations.
|
||||
|
||||
## Spec Sections at a Glance
|
||||
|
||||
| Section | Topic | When to Read |
|
||||
|---------|-------|--------------|
|
||||
| §1–4 | Data model, normalization, decoding | Implementing encoders/decoders |
|
||||
| §5–6 | Syntax, headers, root form | Implementing parsers |
|
||||
| §7 | Strings, keys, quoting, escaping | Implementing string handling |
|
||||
| §8–10 | Objects, arrays, list items | Implementing structure encoding |
|
||||
| §11–12 | Delimiters, indentation, whitespace | Implementing formatting and validation |
|
||||
| §13 | Conformance, options, key folding/path expansion | Implementing options and features |
|
||||
| §14 | Strict-mode errors | Implementing validators |
|
||||
| §15–16 | Security, internationalization | Operational considerations |
|
||||
| §17–19 | IANA, versioning, IP | Ecosystem and licensing |
|
||||
|
||||
## Conformance Checklists
|
||||
|
||||
The spec includes three conformance checklists:
|
||||
|
||||
### Encoder Checklist (§13.1) <sup>[↗ SPEC.md](https://github.com/toon-format/spec/blob/main/SPEC.md#131-encoder-conformance-checklist)</sup>
|
||||
|
||||
Key requirements:
|
||||
- Produce UTF-8 with LF line endings
|
||||
- Use consistent indentation (default 2 spaces, no tabs)
|
||||
- Escape `\\`, `\"`, `\n`, `\r`, `\t` in quoted strings, and use `\uXXXX` for any other U+0000–U+001F control character; lone surrogates are rejected
|
||||
- Quote strings with active delimiter, colon, or structural characters
|
||||
- Emit array lengths `[N]` matching actual count
|
||||
- Preserve object key order
|
||||
- Emit numbers per §2 (canonical decimal in `[1e-6, 1e21)` or zero; exponent form permitted outside)
|
||||
- Convert `-0` to `0`, `NaN`/±Infinity to `null`
|
||||
- Emit booleans and null as lowercase literals (`true`, `false`, `null`)
|
||||
- No trailing spaces or trailing newline
|
||||
- When `keyFolding="safe"` is enabled, folding MUST follow §13.4:
|
||||
- Only fold IdentifierSegment keys (letters/digits/underscores, no dots),
|
||||
- Do not introduce collisions with existing sibling keys,
|
||||
- Do not fold segments that would require quoting.
|
||||
- When `flattenDepth` is set, folding MUST stop at the configured number of segments (§13.4).
|
||||
|
||||
### Decoder Checklist (§13.2) <sup>[↗ SPEC.md](https://github.com/toon-format/spec/blob/main/SPEC.md#132-decoder-conformance-checklist)</sup>
|
||||
|
||||
Key requirements:
|
||||
- Parse array headers per §6 (length, delimiter, fields)
|
||||
- Split inline arrays and tabular rows using active delimiter only
|
||||
- Unescape quoted strings with only valid escapes
|
||||
- Type unquoted primitives: true/false/null → booleans/null, numeric → number, else → string
|
||||
- Enforce strict-mode rules when `strict=true`
|
||||
- Preserve array order and object key order
|
||||
- When `expandPaths="safe"` is enabled, expand dotted keys into nested objects per §13.4:
|
||||
- Split on `.`, only expand when all segments are IdentifierSegments,
|
||||
- Deep-merge overlapping paths (object + object),
|
||||
- Do not perform element-wise array merges.
|
||||
- With `expandPaths="safe"` and `strict=true` (default), MUST error on any expansion conflict (§14.3).
|
||||
- With `expandPaths="safe"` and `strict=false`, MUST apply deterministic last-write-wins (LWW) conflict resolution (§13.4).
|
||||
|
||||
### Validator Checklist (§13.3) <sup>[↗ SPEC.md](https://github.com/toon-format/spec/blob/main/SPEC.md#133-validator-conformance-checklist)</sup>
|
||||
|
||||
Validators should verify:
|
||||
- Structural conformance (headers, indentation, list markers)
|
||||
- Whitespace invariants (no trailing spaces/newlines)
|
||||
- Delimiter consistency between headers and rows
|
||||
- Array length counts match declared `[N]`
|
||||
- All strict-mode requirements (including path-expansion conflicts when enabled)
|
||||
|
||||
## Versioning
|
||||
|
||||
The spec uses semantic versioning (major.minor):
|
||||
- **Major version** (e.g., v2 → v3): Breaking changes, incompatible with previous versions
|
||||
- **Minor version** (e.g., v3.1 → v3.2): Clarifications, additional requirements, or backward-compatible additions
|
||||
|
||||
See [Appendix D: Document Changelog](https://github.com/toon-format/spec/blob/main/SPEC.md#appendix-d-document-changelog-informative) for detailed version history.
|
||||
|
||||
## Contributing to the Spec
|
||||
|
||||
The spec is community-maintained at [github.com/toon-format/spec](https://github.com/toon-format/spec). We welcome contributions of all kinds: reporting ambiguities or errors, proposing clarifications and examples, adding test cases to the reference suite, or discussing edge cases and normative behavior. Your feedback helps shape the format.
|
||||
@@ -0,0 +1,367 @@
|
||||
---
|
||||
description: JSON-to-TOON mappings at a glance for objects, arrays, quoting, key folding, and type conversions.
|
||||
---
|
||||
|
||||
# Syntax Cheatsheet
|
||||
|
||||
Quick reference for mapping JSON to TOON format. For rigorous, normative syntax rules and edge cases, see the [Specification](/reference/spec).
|
||||
|
||||
## Objects
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Ada"
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
id: 1
|
||||
name: Ada
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Nested Objects
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"user": {
|
||||
"id": 1,
|
||||
"name": "Ada"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
user:
|
||||
id: 1
|
||||
name: Ada
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Primitive Arrays
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"tags": ["foo", "bar", "baz"]
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
tags[3]: foo,bar,baz
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Tabular Arrays
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"items": [
|
||||
{ "id": 1, "qty": 5 },
|
||||
{ "id": 2, "qty": 3 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
items[2]{id,qty}:
|
||||
1,5
|
||||
2,3
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Mixed and Non-Uniform Arrays
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"items": [1, { "a": 1 }, "x"]
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
items[3]:
|
||||
- 1
|
||||
- a: 1
|
||||
- x
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
> [!NOTE]
|
||||
> When a list-item object has a tabular array as its first field, the tabular header appears on the hyphen line. Rows are indented two levels deeper than the hyphen, and other fields are indented one level deeper. This is the canonical encoding for this pattern.
|
||||
|
||||
::: code-group
|
||||
|
||||
```yaml [Multi-field object]
|
||||
items[1]:
|
||||
- users[2]{id,name}:
|
||||
1,Ada
|
||||
2,Bob
|
||||
status: active
|
||||
```
|
||||
|
||||
```yaml [Single-field object]
|
||||
items[1]:
|
||||
- users[2]{id,name}:
|
||||
1,Ada
|
||||
2,Bob
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Arrays of Arrays
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"pairs": [[1, 2], [3, 4]]
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
pairs[2]:
|
||||
- [2]: 1,2
|
||||
- [2]: 3,4
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Root Arrays
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
["x", "y", "z"]
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
[3]: x,y,z
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Empty Containers
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [Empty Object]
|
||||
{}
|
||||
```
|
||||
|
||||
```yaml [Empty Object]
|
||||
(empty output)
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [Empty Array]
|
||||
{
|
||||
"items": []
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [Empty Array]
|
||||
items: []
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Quoting Special Cases
|
||||
|
||||
### Strings That Look Like Literals
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"version": "123",
|
||||
"enabled": "true"
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
version: "123"
|
||||
enabled: "true"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
These strings must be quoted because they look like numbers/booleans.
|
||||
|
||||
### Strings Containing Delimiters
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"note": "hello, world"
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
note: "hello, world"
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
Strings must be quoted when they contain the active delimiter (inside an array scope) or the document delimiter (object field values, comma by default).
|
||||
|
||||
### Strings with Leading/Trailing Spaces
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"message": " padded "
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
message: " padded "
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
### Empty String
|
||||
|
||||
::: code-group
|
||||
|
||||
```json [JSON]
|
||||
{
|
||||
"name": ""
|
||||
}
|
||||
```
|
||||
|
||||
```yaml [TOON]
|
||||
name: ""
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
## Quoting Rules Summary
|
||||
|
||||
Strings **must** be quoted if they:
|
||||
|
||||
- Are empty (`""`)
|
||||
- Have leading or trailing whitespace
|
||||
- Equal `true`, `false`, or `null` (case-sensitive)
|
||||
- Look like numbers (e.g., `"42"`, `"-3.14"`, `"1e-6"`, `"05"`)
|
||||
- Contain special characters: `:`, `"`, `\`, `[`, `]`, `{`, `}`, or any control character (U+0000–U+001F, including newline/tab/CR)
|
||||
- Contain the relevant delimiter – the active delimiter inside an array scope, or the document delimiter (comma by default) for object field values
|
||||
- Equal `"-"` or start with `"-"` followed by any character
|
||||
|
||||
Otherwise, strings can be unquoted. Unicode and emoji are safe:
|
||||
|
||||
```yaml
|
||||
message: Hello 世界 👋
|
||||
note: This has inner spaces
|
||||
```
|
||||
|
||||
## Escape Sequences
|
||||
|
||||
Six escape sequences are valid in quoted strings:
|
||||
|
||||
| Character | Escape |
|
||||
|-----------|--------|
|
||||
| Backslash (`\`) | `\\` |
|
||||
| Double quote (`"`) | `\"` |
|
||||
| Newline | `\n` |
|
||||
| Carriage return | `\r` |
|
||||
| Tab | `\t` |
|
||||
| Any other U+0000–U+001F control character | `\uXXXX` |
|
||||
|
||||
Other escapes (e.g., `\x`, `\0`, `\b`) are invalid, and lone-surrogate `\uXXXX` values (U+D800–U+DFFF) are rejected.
|
||||
|
||||
## Array Headers
|
||||
|
||||
### Basic Header
|
||||
|
||||
```
|
||||
key[N]:
|
||||
```
|
||||
|
||||
- `N` = array length
|
||||
- Default delimiter: comma
|
||||
|
||||
### Tabular Header
|
||||
|
||||
```
|
||||
key[N]{field1,field2,field3}:
|
||||
```
|
||||
|
||||
- `N` = array length
|
||||
- `{fields}` = column names
|
||||
- Default delimiter: comma
|
||||
|
||||
### Alternative Delimiters
|
||||
|
||||
::: code-group
|
||||
|
||||
```yaml [Tab Delimiter]
|
||||
items[2 ]{id name}:
|
||||
1 Alice
|
||||
2 Bob
|
||||
```
|
||||
|
||||
```yaml [Pipe Delimiter]
|
||||
items[2|]{id|name}:
|
||||
1|Alice
|
||||
2|Bob
|
||||
```
|
||||
|
||||
:::
|
||||
|
||||
The delimiter symbol appears inside the brackets and braces.
|
||||
|
||||
## Key Folding (Optional)
|
||||
|
||||
Standard nesting:
|
||||
|
||||
```yaml
|
||||
data:
|
||||
metadata:
|
||||
items[2]: a,b
|
||||
```
|
||||
|
||||
With key folding (`keyFolding: 'safe'`):
|
||||
|
||||
```yaml
|
||||
data.metadata.items[2]: a,b
|
||||
```
|
||||
|
||||
See [Format Overview – Key Folding](/guide/format-overview#key-folding-optional) for details.
|
||||
|
||||
## Type Conversions
|
||||
|
||||
| Input | Output |
|
||||
|-------|--------|
|
||||
| Finite number in `[1e-6, 1e21)` (or zero) | Canonical decimal |
|
||||
| Finite number outside that range | Exponent form permitted |
|
||||
| `NaN`, `Infinity`, `-Infinity` | `null` |
|
||||
| `BigInt` (safe range) | Number |
|
||||
| `BigInt` (out of range) | Quoted decimal string |
|
||||
| `Date` | ISO string (quoted) |
|
||||
| `Set` | Array of normalized values |
|
||||
| `Map` | Object with `String(key)` keys |
|
||||
| `undefined`, `function`, `symbol` | `null` |
|
||||
|
||||
::: info
|
||||
TOON itself doesn't specify how `Date` should be encoded – the spec leaves this to implementations. This library emits an ISO 8601 string in quotes; other implementations may choose differently.
|
||||
:::
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { UserConfig } from 'unocss'
|
||||
import { defineConfig, presetIcons, presetWind4, transformerDirectives } from 'unocss'
|
||||
|
||||
const config: UserConfig = defineConfig({
|
||||
presets: [
|
||||
presetWind4(),
|
||||
presetIcons(),
|
||||
],
|
||||
transformers: [
|
||||
transformerDirectives(),
|
||||
],
|
||||
})
|
||||
|
||||
export default config
|
||||
@@ -0,0 +1,10 @@
|
||||
name = "toon-docs"
|
||||
compatibility_date = "2025-10-01"
|
||||
|
||||
[[routes]]
|
||||
pattern = "toonformat.dev"
|
||||
custom_domain = true
|
||||
|
||||
[assets]
|
||||
directory = "./.vitepress/dist/"
|
||||
not_found_handling = "404-page"
|
||||