Reading from a YAML file in Javascript

I am trying to read parameters from a YAML file in Javascript. Is there a good library for this?

I tried these libraries: https://github.com/nodeca/js-yaml and http://code.google.com/p/javascript-yaml-parser/

but both libraries only have functions that parse YAML when given as a string, instead of parsing directly from a .yml or .yaml file. Are there parsers that read YAML from a file and convert them to JS objects?

+4
source share
3 answers

js-yaml . I found this in Googling "node js yaml" because reading from files in JavaScript is done on the server side using node.js (or something like that), and not from the browser.

README for js-yaml begins

Usage: js-yaml [-h] [-v] [-c] [-j] [-t] file

Positional Arguments:

File File with YAML documents

This is pretty convincing evidence that it processes YAML directly from files.

+8
source

It seemed hard to find a good example of using js-yaml from a browser. Perhaps because they emphasize the use of the parser in node.js.

The parser is located at https://github.com/nodeca/js-yaml . Use NPM to install it

npm install js-yaml 

and take the js-yaml.js file from the node_modules / js-yaml / bin directory.

Here is a simple, simple demo that loads a YAML file, uses js-yaml to parse it in objects, and then (to check) it uses its own JSON.stringify to convert JSON to string and finally uses jquery $ .parseJSON to check received JSON

 (function () { "use strict"; $(document).ready(function () { $.get('/common/resources/LessonContentsLv01Ln01.yml') .done(function (data) { console.log('File load complete'); console.log(jsyaml.load(data)); var jsonString = JSON.stringify(data); console.log(jsonString); console.log($.parseJSON(jsonString)); }); }); }()); 

And HTML

 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Read YAML</title> <script src="//code.jquery.com/jquery-2.1.0.js"> </script><script src='/vendor/js/js-yaml.js'> </script><script src='/test/readYaml.js'> </script> </head> <body> </body> </html> 

Github repository https://github.com/nodeca/js-yaml

+5
source

If you want to parse it in a web browser, you can download the yaml file that you want to parse in the script tag and read its contents using js code that will give you the result of the string. And if you want to parse yaml in a nodejs environment, you can read the file directly as well as get a line. I don’t think this is a problem from direct parsing yaml or parse yaml from string.

+1
source

All Articles