How to use the parse function from yaml

Find comprehensive JavaScript yaml.parse code examples handpicked from public code repositorys.

yaml.parse is a function in the YAML library that converts a YAML-formatted string into a JavaScript object.

51
52
53
54
55
56
57
58
59
60
	path.resolve(__dirname, `../content/en/${url == '/' ? 'index' : url}.md`),
	{ encoding: 'utf8' }
);
const name = (route.name && route.name.en) || route.name;
const fm = (content.match(FRONT_MATTER_REG) || [])[1];
const meta = (fm && yaml.parse(`---\n${fm.replace(/^/gm, '  ')}\n`)) || {};
const contentBody = content.replace(FRONT_MATTER_REG, '');
let suffix = '';
for (let pattern in groups) {
	if (url.match(pattern)) {
fork icon475
star icon331
watch icon16

+ 6 other calls in file

8
9
10
11
12
13
14
15
16
17
const prettier = require('prettier');
const { JSDOM } = jsdom;
const configFilePath = path.resolve(currentDir, 'docs', '_data', 'icons.yaml');
const file = fs.readFileSync(configFilePath, 'utf8');
const YAML = require('yaml');
const config = YAML.parse(file);
const { html2xhtml } = require('./util');
const { query } = require('winston');
const genText = 'This is a generated file, DO NOT EDIT';

fork icon69
star icon161
watch icon0

How does yaml.parse work?

yaml.parse works by taking a YAML-formatted string as input and parsing it into a JavaScript object.

The function uses a YAML parser to interpret the string and convert it into a data structure that can be manipulated in JavaScript.

The resulting object may contain nested objects, arrays, and scalar values such as strings, numbers, and booleans, depending on the contents of the YAML input.

If the YAML input is invalid or cannot be parsed for any reason, an error is thrown.

yaml.parse is useful when working with configuration files, data interchange formats, and other text-based data that is often stored or transmitted in a YAML format.

940
941
942
943
944
945
946
947
948
949
if (weakEnumList === undefined) {
  let f = this.global.resource('weak-enum-list');
  // NOTE: This has to be sync, so we can use this data in if conditions.
  if (f) {
    let rawData = fs.readFileSync(f, { encoding: 'utf8', flag: 'r' });
    weakEnumList = YAML.parse(rawData);
  } else {
    weakEnumList = [
      'AttributeWritePermission',
      'BarrierControlBarrierPosition',
fork icon65
star icon91
watch icon21

+ 2 other calls in file

14
15
16
17
18
19
20
21
22
23
24
25
26


const availableLanguages = ['fr', 'en-us'] //, 'es', 'it'] For now, we don't want es and it to be compile (it could create compilation errors).
const defaultLang = availableLanguages[0]


const readYAML = (path) => {
	return yaml.parse(fs.readFileSync(path, 'utf-8'))
}


const writeYAML = (path, content, blockQuote = 'literal', sortMapEntries) => {
	resolveConfig(process.cwd()).then((prettierConfig) =>
fork icon54
star icon122
watch icon7

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const yaml = require("js-yaml");

const yamlString = `
- name: John
age: 32
interests:
- programming
- hiking
- name: Sarah
age: 28
interests:
- photography
- yoga
`;

const data = yaml.safeLoad(yamlString);

console.log(data);

In this example, we use yaml.parse to convert a YAML-formatted string into a JavaScript object. We define a YAML-formatted string that contains an array of objects, each representing a person with a name, age, and list of interests. We then call yaml.safeLoad with the YAML string to parse it into a JavaScript object, which we store in the data variable. We log the contents of data to the console, which will display an array of JavaScript objects representing the people and their attributes. By using yaml.parse in this way, we can easily convert YAML-formatted data into a format that can be manipulated in JavaScript.

20
21
22
23
24
25
26
27
28
29
const loadContracts = () => {
  // Load env
  let env = process.env
  if (fs.existsSync('./env.yml')) {
    const file = fs.readFileSync('./env.yml', 'utf8')
    env = YAML.parse(file)
  }
  const L2_NODE_WEB3_URL = env.L2_NODE_WEB3_URL || process.env.L2_NODE_WEB3_URL
  const PRIVATE_KEY = env.PRIVATE_KEY || process.env.PRIVATE_KEY
  const BOBA_GASPRICEORACLE_ADDRESS =
fork icon52
star icon51
watch icon6

376
377
378
379
380
381
382
383
384
385

const projectTitle = this.wPkg('slugName')

const file = fs.readFileSync( this.wordupDockerPath('docker-compose.dev.yml') , 'utf8')

let dockerComposeSettings = YAML.parse(file)

// Check if WP docker container should be build on system
if(build){
  let buildArgs = {}
fork icon15
star icon119
watch icon0

135
136
137
138
139
140
141
142
143
144

const pathOfAppFileInSource = path.join(
    pathOfSourceDirectoryApps,
    appFileName
)
const contentParsed = yaml.parse(
    fs.readFileSync(pathOfAppFileInSource, 'utf-8')
)

//v4
fork icon13
star icon19
watch icon0

+ 3 other calls in file

7
8
9
10
11
12
13
14
15
16
17
18
19


describe('GraphQLLDParser', function () {


  before(function () {
    const file = fs.readFileSync(path.resolve(__dirname, CONFIG_FILE), 'utf8');
    this.yamlData = YAML.parse(file);
    const options = {defaultDataSources: this.yamlData['x-walder-datasources'], cache: true};


    this.output = parseGraphQLLD(this.yamlData.paths['/movies/{actor}']['get']['x-walder-query'], options);
    this.sortingOptionsOutput = parseGraphQLLD(this.yamlData.paths['/music/{musician}/sorted']['get']['x-walder-query'], options);
fork icon9
star icon58
watch icon7

+ 5 other calls in file

13
14
15
16
17
18
19
20
21
22
23
24


describe('GraphQLLDValidator', function () {
  {
    before(function () {
      const file = fs.readFileSync(Path.resolve(__dirname, CONFIG_FILE), 'utf8');
      const yamlData = YAML.parse(file);


      const path = '/movies/{actor}';
      const method = 'get';

fork icon9
star icon58
watch icon7

+ 5 other calls in file

453
454
455
456
457
458
459
460
461
462
463
const yaml = {
  load() {
    const path = join(...arguments)
    const file = path.endsWith(".yaml") ? path : join(path, "index.yaml")
    const content = readFileSync(path, "utf8")
    return YAML.parse(content)
  },
}


const json = {
fork icon4
star icon25
watch icon2

+ 20 other calls in file

160
161
162
163
164
165
166
167
168
169
      },
    },
  ],
],
customFields: {
  numbersSpec: YAML.parse(numbersSpec),
  numbersSpecLink: `${customConfig.numbersSpecLink}`,
  phoneNumberLookupSpec: YAML.parse(phoneNumberLookupSpec),
  phoneNumberLookupSpecLink: `${customConfig.phoneNumberLookupSpecLink}`,
  voiceSpec: YAML.parse(voiceSpec),
fork icon37
star icon18
watch icon42

+ 35 other calls in file

16
17
18
19
20
21
22
23
24
25
fileContent = fileContent.toString();
const extension = file.split(".").pop();

try {
  if (extension === "yml" || extension == "yaml") {
    dataObject = YAML.parse(fileContent);
  } else {
    dataObject = JSON.parse(fileContent);
  }
} catch (e) {
fork icon3
star icon6
watch icon2

+ 4 other calls in file

316
317
318
319
320
321
322
323
324
325
    } else {
        configValues.push(`${k}=${v}`);
    }
}
let outputError = "";
let manifest = YAML.parse(fs.readFileSync(`${APPLET_FOLDER}/${name}/manifest.yaml`, 'utf-8'));
let appletContents = fs.readFileSync(`${APPLET_FOLDER}/${name}/${manifest.fileName}`).toString();
if(process.env.REDIS_HOSTNAME != undefined) {
    if(appletContents.indexOf(`load("cache.star", "cache")`) != -1) {
        const redis_connect_string = `cache_redis.connect("${ process.env.REDIS_HOSTNAME }", "${ process.env.REDIS_USERNAME }", "${ process.env.REDIS_PASSWORD }")`
fork icon2
star icon3
watch icon0

576
577
578
579
580
581
582
583
584
585
586
    errorHandler(error);
  }
}


function findTestRows(testContent) {
  const testYAML = yaml.parse(testContent, (options = { maxAliasCount: -1 }));
  const testNames = Object.keys(testYAML);
  const testRows = testContent.split("\n");
  const indexes = {};
  testNames.forEach((testName) => {
fork icon1
star icon3
watch icon1

307
308
309
310
311
312
313
314
315

  return {cas, current, ...{compiled, stack_revision, stack_path}, services_slices};
}


async parse() {
  let {compiled} = await this._compute();
  return compiled;
}
fork icon1
star icon1
watch icon2

+ 8 other calls in file

19
20
21
22
23
24
25
26
27
28
29
const {basename, dirname, extname} = require('path');


// custom yml/yaml formatter
['yaml', 'yml'].forEach(format => {
  nconf.formats[format] = {
    parse: (obj, options) => yaml.parse(obj, options),
    stringify: (obj, options) => yaml.stringify(obj, options),
  };
});

fork icon0
star icon1
watch icon0

+ 15 other calls in file

209
210
211
212
213
214
215
216
217
  // return the plugin.js return first
  if (fs.existsSync(path.join(this.root, 'plugin.js'))) return require(path.join(this.root, 'plugin.js'))(config);
  // otherwise return the plugin.yaml content
  if (fs.existsSync(path.join(this.root, 'plugin.yaml'))) return yaml.parse(fs.readFileSync(path.join(this.root, 'plugin.yaml'), 'utf8'));
  // otherwise return the plugin.yml content
  if (fs.existsSync(path.join(this.root, 'plugin.yml'))) return yaml.parse(fs.readFileSync(path.join(this.root, 'plugin.yml'), 'utf8'));
  // otherwise return uh, nothing?
  return {};
}
fork icon0
star icon1
watch icon0

+ 31 other calls in file

53
54
55
56
57
58
59
60
61
62
    }
    break;
}
case 'yaml': {
    try {
        yaml.parse(value);
        resolve(false);
    } catch (e) {
        resolve(e.message);
    }
fork icon162
star icon0
watch icon24

+ 2 other calls in file

54
55
56
57
58
59
60
61
62
63
	console.log("No YAML " + yml_path + ")");
	return null;
}

const y_file = fs.readFileSync(yml_path, 'utf8');
const yml = YAML.parse(y_file);
var platform = null;

if (typeof (yml) !== "undefined") {
	platform = Object.keys(yml)[0];
fork icon8
star icon21
watch icon4

+ 4 other calls in file

769
770
771
772
773
774
775
776
777
778
779
780
781
782
}


function process_file(p_FileName) {
    const l_FileContent = read_file(`${g_Directory}\\${p_FileName}`);


    const l_Config = YAML.parse(l_FileContent);


    const l_Types = [];


    for (let [i_TypeName, i_Type] of Object.entries(l_Config.types)) {
fork icon0
star icon1
watch icon0