0
# Parse & Stringify
1
2
Simple parsing and stringifying functions for converting between YAML strings and JavaScript values. This is the most commonly used API layer, perfect for configuration files, data serialization, and straightforward YAML processing.
3
4
## Capabilities
5
6
### Parse Function
7
8
Parses a YAML string into JavaScript values. Supports single document parsing with comprehensive error handling and reviver function support similar to JSON.parse.
9
10
```typescript { .api }
11
/**
12
* Parse YAML string into JavaScript values
13
* @param src - YAML string to parse
14
* @param reviver - Optional reviver function for transforming values
15
* @param options - Parsing and schema options
16
* @returns Parsed JavaScript value
17
*/
18
function parse(src: string, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions): any;
19
function parse(src: string, reviver: Reviver, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions): any;
20
21
type Reviver = (key: unknown, value: unknown) => unknown;
22
```
23
24
**Usage Examples:**
25
26
```typescript
27
import { parse } from "yaml";
28
29
// Basic usage
30
const config = parse(`
31
database:
32
host: localhost
33
port: 5432
34
credentials:
35
username: admin
36
password: secret
37
`);
38
// Result: { database: { host: 'localhost', port: 5432, credentials: { username: 'admin', password: 'secret' } } }
39
40
// With reviver function
41
const data = parse('count: "42"', (key, value) => {
42
if (key === 'count') return parseInt(value as string);
43
return value;
44
});
45
// Result: { count: 42 }
46
47
// With options
48
const strictData = parse(`
49
name: John
50
age: 30
51
`, {
52
strict: true,
53
prettyErrors: true
54
});
55
```
56
57
### Stringify Function
58
59
Converts JavaScript values to YAML strings. Supports replacer functions, custom formatting options, and complete control over output style.
60
61
```typescript { .api }
62
/**
63
* Convert JavaScript values to YAML string
64
* @param value - Value to convert to YAML
65
* @param replacer - Optional replacer function or array for filtering
66
* @param options - Formatting and schema options
67
* @returns YAML string representation
68
*/
69
function stringify(
70
value: any,
71
options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions
72
): string;
73
74
function stringify(
75
value: any,
76
replacer?: Replacer | null,
77
options?: string | number | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions)
78
): string;
79
80
type Replacer = (key: string, value: any) => any | Array<string | number>;
81
```
82
83
**Usage Examples:**
84
85
```typescript
86
import { stringify } from "yaml";
87
88
// Basic usage
89
const yamlString = stringify({
90
name: "Alice",
91
hobbies: ["reading", "coding", "music"],
92
address: {
93
city: "New York",
94
zipcode: 10001
95
}
96
});
97
// Result:
98
// name: Alice
99
// hobbies:
100
// - reading
101
// - coding
102
// - music
103
// address:
104
// city: New York
105
// zipcode: 10001
106
107
// With replacer function
108
const filtered = stringify({
109
username: "john",
110
password: "secret",
111
email: "john@example.com"
112
}, (key, value) => {
113
if (key === 'password') return '***';
114
return value;
115
});
116
117
// With formatting options
118
const formatted = stringify(data, {
119
indent: 4,
120
blockQuote: 'literal',
121
lineWidth: 120
122
});
123
124
// Shorthand indent specification
125
const indented = stringify(data, null, 2); // 2-space indent
126
```
127
128
### Error Handling
129
130
Both functions handle errors gracefully and provide detailed error information for debugging.
131
132
```typescript { .api }
133
// Parse errors are thrown as YAMLParseError
134
try {
135
const data = parse('invalid: yaml: content:');
136
} catch (error) {
137
if (error instanceof YAMLParseError) {
138
console.log(error.message); // Detailed error message
139
console.log(error.pos); // [start, end] position in source
140
console.log(error.linePos); // { line: number, col: number }
141
}
142
}
143
144
// Stringify typically doesn't throw but may warn
145
const result = stringify(undefined, { keepUndefined: false });
146
// Returns undefined instead of throwing
147
```
148
149
## Option Interfaces
150
151
### ParseOptions
152
153
```typescript { .api }
154
interface ParseOptions {
155
/** Keep CST nodes in parsed output */
156
keepCstNodes?: boolean;
157
/** Keep node type information */
158
keepNodeTypes?: boolean;
159
/** Keep Uint8Array instances as-is in JSON output */
160
keepBlobsInJSON?: boolean;
161
/** Maximum number of alias nodes to resolve */
162
maxAliasCount?: number;
163
/** Add line/column position info to errors */
164
prettyErrors?: boolean;
165
/** Callback for each new line during parsing */
166
lineCounter?: LineCounter | boolean;
167
/** Log level for warnings and errors */
168
logLevel?: 'silent' | 'error' | 'warn' | 'debug';
169
/** Enable strict parsing mode */
170
strict?: boolean;
171
}
172
```
173
174
### ToStringOptions
175
176
```typescript { .api }
177
interface ToStringOptions {
178
/** Use block quote style for multiline strings */
179
blockQuote?: boolean | 'folded' | 'literal';
180
/** Default type for object keys */
181
defaultKeyType?: Scalar.Type | null;
182
/** Default type for string values */
183
defaultStringType?: Scalar.Type;
184
/** Include document directives */
185
directives?: boolean | null;
186
/** Number of spaces for indentation */
187
indent?: number;
188
/** Use block style for sequences */
189
indentSeq?: boolean | null;
190
/** Maximum line width before folding */
191
lineWidth?: number;
192
/** Minimum width for single-line collections */
193
minContentWidth?: number;
194
/** Use null instead of empty for null values */
195
nullStr?: string;
196
/** Use single quotes by default */
197
singleQuote?: boolean | null;
198
}
199
```
200
201
### DocumentOptions
202
203
```typescript { .api }
204
interface DocumentOptions {
205
/** Document schema version */
206
version?: '1.1' | '1.2' | 'next';
207
/** Custom tags to include */
208
customTags?: (TagId | Tag)[];
209
/** Log level for this document */
210
logLevel?: 'silent' | 'error' | 'warn' | 'debug';
211
/** Schema to use for parsing */
212
schema?: 'core' | 'failsafe' | 'json' | 'yaml-1.1';
213
/** Sort object keys */
214
sortMapEntries?: boolean | ((a: Pair, b: Pair) => number);
215
/** Anchor prefix for generated anchors */
216
anchorPrefix?: string;
217
/** Keep undefined values */
218
keepUndefined?: boolean;
219
}
220
```