Converting YAML and JSON Both Ways in React
You can convert YAML and JSON with the parse() and stringify() functions of the npm yaml package. To convert YAML to JSON, call parse() to read the YAML and pass the result to JSON.stringify(). To convert JSON to YAML, call JSON.parse() to read the JSON and pass the result to stringify().
However, several things trip you up if you use the functions without options. The JSON string "no" is written out as the unquoted no, which a YAML 1.1 reader turns into false. The merge key <<: *base is not expanded. In this article, I check these points and build a YamlJsonConverter component that converts between two panes.
The test environment was Ubuntu 24.04, Node.js 22.23.4, and Chromium 153. I used yaml 2.9.1, react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, esbuild 0.28.2, and Playwright 1.63.0. I checked the conversion functions in Node.js. For the component, I confirmed there were no type errors with tsc, then ran the development build wrapped in StrictMode and operated it from Playwright in Chromium at a width of 375px. I did not test Firefox, Safari, real smartphones, YAML files several megabytes in size, conversion of multiple documents separated by ---, or conversion that keeps comments.

The conversion functions
I put the conversion logic in convert.ts. Both yamlToJson() and jsonToYaml() return the converted string, an error message, and a warning message.
// Functions that convert between YAML and JSON
import { parse, stringify, YAMLParseError } from 'yaml';
export type Converted =
| { text: string; error: ''; warning: string }
| { text: ''; error: string; warning: '' };
const empty: Converted = { text: '', error: '', warning: '' };
function fail(error: string): Converted {
return { text: '', error, warning: '' };
}
// Turn an error thrown by yaml into a short message with line and column
function yamlErrorMessage(e: unknown): string {
if (e instanceof YAMLParseError) {
// The first line of message is "<reason> at line 2, column 1:". From the second line on, it shows the excerpt around the error
const reason = e.message.split('\n')[0].replace(/ at line \d+, column \d+:$/, '');
const where = e.linePos ? `${e.linePos[0].line}行目・${e.linePos[0].col}列目` : '位置不明';
return `YAML として読めません(${where}、${e.code}):${reason}`;
}
if (e instanceof ReferenceError) {
// ReferenceError is thrown when alias expansion exceeds maxAliasCount, and when
// a name that is not defined with & is referenced with *name
if (e.message.startsWith('Excessive alias count')) {
return 'YAML のエイリアス(*名前)の展開が多すぎるため、変換をやめました';
}
return `YAML のエイリアスを読めません:${e.message}`;
}
return `YAML として読めません:${(e as Error).message}`;
}
export function yamlToJson(source: string): Converted {
if (source.trim() === '') return empty;
let value: unknown;
try {
// merge: true expands merge keys (<<: *name). It is off by default in YAML 1.2
value = parse(source, { merge: true, maxAliasCount: 100 });
} catch (e) {
return fail(yamlErrorMessage(e));
}
// .inf and .nan are not valid JSON values, and JSON.stringify turns them into null. Count how many there are
let lost = 0;
const text = JSON.stringify(
value,
(_key, v) => {
if (typeof v === 'number' && !Number.isFinite(v)) lost++;
return v;
},
2,
);
const warning = lost > 0 ? `JSON で表せない数(.inf、.nan)が ${lost} か所あり、null にしました` : '';
return { text: text + '\n', error: '', warning };
}
export function jsonToYaml(source: string): Converted {
if (source.trim() === '') return empty;
let value: unknown;
try {
value = JSON.parse(source);
} catch (e) {
return fail(`JSON として読めません:${(e as Error).message}`);
}
// compat: 'yaml-1.1' also quotes strings that YAML 1.1 reads as booleans or dates (no, on, 2024-01-01, etc.)
// lineWidth: 0 keeps long strings from being folded across lines
const text = stringify(value, { compat: 'yaml-1.1', lineWidth: 0 });
return { text, error: '', warning: '' };
}
When I passed the following YAML to yamlToJson() and then passed the resulting JSON to jsonToYaml(), I got back YAML with the same shape as the original. When I converted that YAML to JSON again, I got the same string as the first JSON. However, the comment # 猫の情報 on the first line does not go into the JSON, so it is gone from the YAML I got back.
# Cat information
name: たま
age: 3
indoor: true
answer: "no"
birthday: "2022-04-01"
toys:
- ねずみ
- ボール
owner:
name: Sato
city: Tokyo
note: |
ごはんは朝と夜。
水はいつも新しく。
{
"name": "たま",
"age": 3,
"indoor": true,
"answer": "no",
"birthday": "2022-04-01",
"toys": [
"ねずみ",
"ボール"
],
"owner": {
"name": "Sato",
"city": "Tokyo"
},
"note": "ごはんは朝と夜。\n水はいつも新しく。\n"
}
The | in note keeps the line breaks as they are. In JSON, it becomes a single string that contains \n. When I converted it back to YAML, it was written out again in the | form.
Things to watch for when converting YAML to JSON
no and yes stay strings in YAML 1.2
The yaml package reads a document without a %YAML directive as YAML 1.2 (options reference). In the default YAML 1.2 schema (core), no and yes are not booleans. When I converted a: no, I got "a": "no".
In YAML 1.1, words such as no, yes, and on are treated as booleans. To compare, I read the same input with version: '1.1', and the results changed a lot.
| YAML | YAML 1.2 (default) | YAML 1.1 |
|---|---|---|
a: no |
"a": "no" |
"a": false |
b: yes |
"b": "yes" |
"b": true |
n: 017 |
"n": 17 |
"false": 15 |
d: 2024-01-01 |
"d": "2024-01-01" |
"d": "2024-01-01T00:00:00.000Z" |
In the n: 017 line, even the key n became false, and 017 was read as octal 15. In YAML 1.1 the date is also read as a date, so JSON gets a string with a time attached. The component in this article reads input as the default YAML 1.2.
Expand merge keys with merge: true
A value named with &base can be used elsewhere with *base (anchors and aliases). JSON has no such mechanism, so parse() expands the contents at the alias position. cat: *base became "cat": { "color": "white" }.
On the other hand, the merge key <<: *base, which pulls keys from another map into the current one, is a YAML 1.1 feature and is not in the 1.2 specification. For that reason, the default for the merge option is false in YAML 1.2 (merge key reference). When I read the input without it, << stayed as a literal key.
base: &base
color: white
cat:
<<: *base
name: tama
--- Comparison: parse without merge
{"base":{"color":"white"},"cat":{"<<":{"color":"white"},"name":"tama"}}
With merge: true in yamlToJson(), the output expanded to "cat": { "color": "white", "name": "tama" }.
Set a limit on alias expansion
Aliases multiply when they are expanded. Suppose a 9-element array is referenced 9 times on the next line, and that line is referenced 9 times on the line after that, stacked 10 levels deep. Even though the input is only 10 lines, the expanded array has 9 to the 10th power (about 3.5 billion) elements.
a: &a [x, x, x, x, x, x, x, x, x]
b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a]
c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b]
(d から i も同じ形で続く)
j: &j [*i, *i, *i, *i, *i, *i, *i, *i, *i]
The yaml package has a maxAliasCount option that stops this kind of expansion. Its default is 100. When the limit is reached, it throws a ReferenceError (error reference). When I passed the YAML above to yamlToJson(), it returned a Japanese message that means "Too many alias (*name) expansions, so the conversion was stopped." The 100 in yamlToJson() matches the default, but I set it explicitly so the limit is visible in the code.
A ReferenceError is also thrown when a name that is not defined with & is referenced with *. When I passed a: *nope to yamlToJson(), the error message was Unresolved alias (the anchor must be set before the alias): nope. The message for hitting the limit was Excessive alias count indicates a resource exhaustion attack. If I only mistyped the name after *, I did not want the message to say "too many expansions", so yamlErrorMessage() separates the two cases by checking whether the message starts with Excessive alias count. This wording is not documented, so when you upgrade the yaml version, check that the split still works.
When it can't be read, report the line, column, and error type
When parse() cannot read the input as YAML, it throws a YAMLParseError. linePos holds the line and column counted from 1, and code holds the error type (error reference). For YAML indented with a tab, message was the following string. The first line has the reason and the position, and from the second line on, there is an excerpt around the error. yamlErrorMessage() uses only the reason, with the position part removed from the first line.
"Tabs are not allowed as indentation at line 2, column 1:\n\na:\n\tb: 1\n^\n"
| Input | Error from yamlToJson() (the part after the "Cannot read as YAML" prefix) |
|---|---|
| Indented with a tab | line 2, column 1, TAB_AS_INDENT: Tabs are not allowed as indentation |
| Misaligned indentation | line 3, column 1, BAD_INDENT: All mapping items must start at the same column |
| The same key appears twice | line 2, column 1, DUPLICATE_KEY: Map keys must be unique |
Two documents separated by --- |
line 2, column 1, MULTIPLE_DOCS: Source contains multiple documents; please use YAML.parseAllDocuments() |
parse() reads only one document. To handle multiple documents separated by ---, use parseAllDocuments() (parse reference).
.inf and .nan become null in JSON
YAML's .inf and .nan are read as JavaScript's Infinity and NaN. JSON has no way to write these values, so JSON.stringify() outputs null. To avoid silently changing values, I count the numbers in the replacer function passed as the second argument to JSON.stringify() and show a warning. When I converted speed: .inf, ratio: .nan, and list: [1, -.inf], all three became null, and the component showed a warning that 3 numbers (.inf, .nan) could not be expressed in JSON and were set to null.
Large integers such as 12345678901234567890 also lose precision. When read from YAML, this value became 12345678901234567000. Digits beyond what a JavaScript number can represent exactly are lost before the JSON is produced.
Things to watch for when converting JSON to YAML
Quote strings that YAML 1.1 would read differently, using compat
stringify() adds quotes to strings that would otherwise be read as a different value. The string "123" was written as num: "123" with quotes. However, no and on, which YAML 1.2 reads as strings, were written without quotes.
--- Comparison: stringify without compat
answer: no
flag: on
date: 2024-01-01
code: "017"
num: "123"
y: y
When this YAML is read by a tool that uses YAML 1.1, answer becomes false, and date becomes a date. With compat: 'yaml-1.1', the output uses forms that YAML 1.1 reads as the same value (options reference). In jsonToYaml(), the output had quotes like this. The key y also gets quotes.
answer: "no"
flag: "on"
date: "2024-01-01"
code: "017"
num: "123"
"y": "y"
Don't fold long strings with lineWidth: 0
By default, stringify() folds long strings at about 80 characters (the default lineWidth is 80). A string made of the word neko (cat) repeated 30 times, separated by spaces, was split across two lines without options.
--- Comparison: stringify without lineWidth
memo: ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ ねこ
ねこ ねこ ねこ ねこ ねこ
When I read the folded YAML with parse(), it gave the same string as the original single-line value. However, one string looked as if it were split across two lines, which is confusing, so I stopped the folding with lineWidth: 0.
For invalid JSON, show the JSON.parse() message as is
JSON.parse() throws a SyntaxError when it gets a string that does not match JSON syntax. jsonToYaml() shows that message as is. For {"a": 1,}, the output was "Cannot read as JSON: Expected double-quoted property name in JSON at position 8 (line 1 column 9)".
The component that converts between two panes
import { useId, useState } from 'react';
import { jsonToYaml, yamlToJson } from './convert';
type Side = 'yaml' | 'json';
export function YamlJsonConverter({ initialYaml = '' }: { initialYaml?: string }) {
const id = useId();
const [yaml, setYaml] = useState(initialYaml);
const [json, setJson] = useState(() => yamlToJson(initialYaml).text);
// The side that was edited last, and the error and warning from converting it
const [edited, setEdited] = useState<Side>('yaml');
const [error, setError] = useState('');
const [warning, setWarning] = useState('');
function update(side: Side, text: string) {
const result = side === 'yaml' ? yamlToJson(text) : jsonToYaml(text);
if (side === 'yaml') setYaml(text);
else setJson(text);
setEdited(side);
setError(result.error);
setWarning(result.warning);
// If the input can't be read, keep the other side at its previous result
if (result.error === '') {
if (side === 'yaml') setJson(result.text);
else setYaml(result.text);
}
}
// The side opposite an error keeps its previous result, so gray out its text
const stale = (side: Side) => error !== '' && edited !== side;
return (
<div className="yaml-json">
{(['yaml', 'json'] as const).map((side) => (
<div key={side} className="pane">
<label htmlFor={`${id}-${side}`}>{side === 'yaml' ? 'YAML' : 'JSON'}</label>
<textarea
id={`${id}-${side}`}
rows={13}
spellCheck={false}
value={side === 'yaml' ? yaml : json}
aria-invalid={error !== '' && edited === side}
aria-describedby={edited === side && (error || warning) ? `${id}-message` : undefined}
className={stale(side) ? 'stale' : undefined}
onChange={(e) => update(side, e.target.value)}
/>
{edited === side && (error || warning) && (
<p id={`${id}-message`} className={error ? 'error' : 'warning'} role={error ? 'alert' : 'status'}>
{error || warning}
</p>
)}
</div>
))}
</div>
);
}
.yaml-json {
display: grid;
gap: 12px;
max-width: 560px;
}
.yaml-json .pane {
display: grid;
gap: 4px;
}
.yaml-json label {
font-weight: bold;
}
.yaml-json textarea {
font-family: ui-monospace, monospace;
font-size: 14px;
color: #1f2a30;
padding: 6px 8px;
border: 1px solid #00c8e8;
border-radius: 6px;
}
.yaml-json textarea[aria-invalid='true'] {
border-color: #d85878;
}
/* On error, the other side keeps its previous result. Gray it out to show that it no longer matches the current input */
.yaml-json textarea.stale {
color: #9aa5ab;
}
.yaml-json .error,
.yaml-json .warning {
margin: 0;
font-size: 14px;
}
.yaml-json .error {
color: #d85878;
}
.yaml-json .warning {
color: #067a98;
}
When the YAML textarea changes, update('yaml', …) runs, and the JSON textarea is replaced with the result of yamlToJson(). The JSON textarea works the same way in reverse. Each time the user edits either textarea, the other one is rebuilt. For that reason, I keep the text of both textareas in state, and do the conversion inside the event handler.
While the input can't be read, keep the other pane at its last result
While you are typing YAML, the input is often unreadable. If I emptied the JSON textarea each time, the last good result would disappear. So on an error, I leave the other textarea unchanged and keep its previous result. To show that it no longer matches the current input, I gray out its text (#9aa5ab) instead.
The image above shows the city line in the YAML textarea indented with a tab. The YAML textarea gets aria-invalid="true", so its border turns pink, and a role="alert" message appears under it. The JSON textarea keeps its previous content, and its text color becomes rgb(154, 165, 171). When I changed the tab back to spaces and set city to Osaka, the message disappeared, the JSON textarea became "city": "Osaka", and the text color returned to normal.
The same thing happens from the JSON side. If I leave a , after the last JSON value, the JSON textarea gets a pink border, and the text in the YAML textarea turns gray.
For a conversion that succeeds but still needs to tell the user something, such as the .inf case, the message appears in light blue text with role="status". When I entered speed: .inf and ratio: .nan in the YAML textarea, the JSON textarea became "speed": null and "ratio": null, and a message appeared saying that 2 numbers (.inf, .nan) could not be expressed in JSON and were set to null.





