在Javascript中从YAML文件中读取

nsa*_*x91 10 javascript parsing yaml

我试图将YAML文件中的参数读入Javascript.有没有好的图书馆呢?

我试过这些库:https://github.com/nodeca/js-yamlhttp://code.google.com/p/javascript-yaml-parser/

但是这两个库只有在将YAML作为字符串给出时解析YAML的函数,而不是直接从.yml或.yaml文件解析.是否有任何解析器从文件读取YAML并将它们转换为JS对象?

Ray*_*oal 12

js-yaml.我通过Googling"node js yaml"找到了这个,因为从JavaScript中的文件读取是在服务器端使用node.js(或类似的东西)完成的,而不是从浏览器中读取.

js-yaml的自述文件开始了

用法:js-yaml [-h] [-v] [-c] [-j] [-t]文件

位置参数:

带有YAML文档的文件文件

这是非常有力的证据,它确实直接从文件处理YAML.


wol*_*ent 11

似乎很难找到一个从浏览器中使用js-yaml的好例子.可能是因为他们强调在node.js中使用解析器.

解析器位于https://github.com/nodeca/js-yaml.使用NPM进行安装

npm install js-yaml
Run Code Online (Sandbox Code Playgroud)

并从node_modules/js-yaml/bin目录中获取js-yaml.js文件.

这是一个快速,简单的演示,它加载一个YAML文件,使用js-yaml将其解析为对象,然后(用于验证)它使用本机JSON.stringify将JSON转换为字符串,最后使用jquery $ .parseJSON验证生成的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));
      });
    });
}());
Run Code Online (Sandbox Code Playgroud)

和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>
Run Code Online (Sandbox Code Playgroud)

Github存储库https://github.com/nodeca/js-yaml