Converting between YAML and JSON is a daily task for developers working with configs, APIs, and CI pipelines. Here's a browser-only tool with auto-detection and round-trip accuracy.
Try it: https://devnestio.pages.dev/yaml-json-converter/
YAML Parser (minimal, no dependencies)
The core challenge: parsing indented YAML into a JS object.
function parseYamlLines(lines, startIdx, parentIndent) {
const result = {};
const arr = [];
let isArr = null;
let i = startIdx;
while (i < lines.length) {
const stripped = lines[i].replace(/#.*$/, '').trimEnd();
if (stripped.trim() === '') { i++; continue; }
const indent = stripped.length - stripped.trimStart().length;
if (indent <= parentIndent) break;
const line = stripped.trimStart();
if (line.startsWith('- ')) {
isArr = true;
arr.push(parseScalar(line.slice(2).trim()));
i++;
} else if (line.includes(': ') || line.endsWith(':')) {
isArr = false;
const colonIdx = line.indexOf(': ');
const key = colonIdx === -1 ? line.slice(0,-1) : line.slice(0,colonIdx);
const val = colonIdx === -1 ? '' : line.slice(colonIdx+2).trim();
if (!val) {
i++;
const sub = parseYamlLines(lines, i, indent);
result[key] = sub.value; i = sub.nextIdx;
} else { result[key] = parseScalar(val); i++; }
} else i++;
}
return { value: isArr ? arr : result, nextIdx: i };
}
Scalar type detection
function parseScalar(v) {
if (v === 'true' || v === 'yes') return true;
if (v === 'false' || v === 'no') return false;
if (v === 'null' || v === '~' || v === '') return null;
if (/^-?\d+$/.test(v)) return parseInt(v, 10);
if (/^-?\d*\.\d+$/.test(v)) return parseFloat(v);
if (v.startsWith('"') && v.endsWith('"')) return v.slice(1,-1);
return v;
}
YAML Serializer
Serializing back to YAML: quote strings that look like keywords.
function yamlStr(s) {
if (s === '') return '""';
if (['true','false','null','yes','no','~'].includes(s)) return `"${s}"`;
if (/^\d+$/.test(s) || /^\d*\.\d+$/.test(s)) return `"${s}"`;
return s;
}
Auto-format detection
function detectFormat(text) {
const t = text.trim();
if (t.startsWith('{') || t.startsWith('[')) return 'json';
try { JSON.parse(t); return 'json'; } catch(_) {}
return 'yaml';
}
Features
- YAML → JSON and JSON → YAML
- Auto-detect input format
- 2-space, 4-space, or tab indentation
- Sort keys alphabetically
- Swap panels to chain conversions
- Download as
.yamlor.json - 97 tests, all passing
DevNestio — browser-only developer tools.
Top comments (0)