JavaScript Yaml Parser

JavaScript YAML Parser

JS-YAML parser works in browser. Here is an online demonstration : https://nodeca.github.io/js-yaml. Though, it's primary goal is node.js, and browser version was done just for fun :)

How to parse YAML in the browser?

Similar question: JavaScript YAML Parser.

The most promising library that seems to work in the browser is js-yaml. A snippet from the project page for loading the library in HTML:

<script src="js-yaml.min.js"></script>
<script type="text/javascript">
var doc = jsyaml.load('greeting: hello\nname: world');
</script>

They claim to also support AMD loaders like RequireJS.

Here is the "browserified" version of the library: with comments and minified.

Parsing a YAML file using js-yaml

{ is a special character in YAML which starts a flow sequence. You need to either quote the scalar that contains it:

key: "{{ val1 }} {{ val2 }}"

or use block scalars:

key: >-
{{ val1 }} {{ val2 }}

Read strongly typed yaml file in Typescript?

From what I can see when using @types/js-yaml is that load is not generic, meaning it does not accept a type parameter.

So the only way to get a type here is to use an assertion, for example:

const yaml = load(await readFile(filepath, "utf8")) as YourType;
const phrases = yaml.trainingPhrases;

Or in short:

const phrases = (load(await readFile(filepath, "utf8")) as YourType).trainingPhrases;

If you absolutely want a generic function, you can easily wrap the original, like:

import {load as original} from 'js-yaml';

export const load = <T = ReturnType<typeof original>>(...args: Parameters<typeof original>): T => load(...args);

And then you can use it as:

const phrases = load<YourType>('....').trainingPhrases;

Pure Javascript YAML library that supports both dump and load?

Possibly newer version of js-yaml here:

http://github.com/visionmedia/js-yaml

Reading from YAML File in Javascript

js-yaml does. I found this by Googling "node js yaml" because reading from files in JavaScript is done server side with node.js (or something like it), not from a browser.

The README for js-yaml begins

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

Positional arguments:

file File with YAML document(s)

That is pretty strong evidence that it does process YAML directly from files.



Related Topics



Leave a reply



Submit