简体   繁体   English

来自JSON的YAML文件

[英]YAML File From JSON

I am trying to create a yaml file from a json file that will be used for cuttle rate limiting and will look something like this ( https://github.com/mrkschan/cuttle/blob/master/cuttle.yml ). 我试图从json文件创建一个yaml文件,该文件将用于cuttle速率限制,看起来像这样( https://github.com/mrkschan/cuttle/blob/master/cuttle.yml )。 This is the code that I have to convert the json file. 这是我必须转换json文件的代码。 (node-yaml: https://www.npmjs.com/package/node-yaml ) (node-yaml: https ://www.npmjs.com/package/node-yaml)

const yaml = require('node-yaml');
const test = require('./test.json');

let converted = yaml.dump(test);
console.log(converted);

Here is the test.json file. 这是test.json文件。

{
"zones": 
    [ 
        { 
            "host": "*", 
            "shared": true, 
            "control": "rps", 
            "rate": 2 
        }, 
        { 
            "host": "github.com", 
            "shared": false, 
            "control": "rpm", 
            "rate": 10
        }
    ] 
}

The output that I get is this. 我得到的输出是这个。

zones:
  - host: '*'
    shared: true
    control: rps
    rate: 2
  - host: github.com
    shared: false
    control: rpm
    rate: 10

It's super close to what I want to output except for the fact that github.com is not "github.com". 除了github.com不是“github.com”之外,它与我想输出的内容非常接近。 If anyone knows how to fix this, please let me know! 如果有人知道如何解决这个问题,请告诉我!

From yaml_format : Strings in YAML can be wrapped both in single and double quotes. 来自yaml_formatYAML中的字符串可以用单引号和双引号括起来。 In some cases, they can also be unquoted . 在某些情况下,它们也可以不加引号

So github.com string value in yaml output is correctly unquoted, and * string value in yaml output is correctly quoted. 因此,yaml输出中的github.com字符串值被正确地github.com引用,并且yaml输出中的*字符串值被正确引用。

If you expect formally correct yaml format you are done. 如果您期望正式的yaml格式,那么您就完成了。
If you expect some different format you should formally define it. 如果您期望某种不同的格式,您应该正式定义它。

In YAML github.com doesn't need quotes. 在YAML中, github.com不需要引号。 With or without it, it represents the same scalar value. 有或没有它,它代表相同的标量值。

But since YAML is a superset of JSON your test.json file already is perfectly fine YAML, and there is absolutely no need to parse it (using a JSON or YAML library) and then dump to YAML. 但由于YAML是JSON的超集,你test.json文件已经完全没有YAML,也绝对没有必要对它进行解析(使用JSON或YAML库),然后转储到YAML。 The only thing your program needs to do is copy (or rename) test.json to test.yaml and you are done. 你的程序唯一需要做的就是将test.json复制(或重命名)为test.yaml ,你就完成了。

As a side note: Your link points to a cuttle.yml , there is no explanation what restrictions they have to use a .yml extension. 作为旁注:您的链接指向cuttle.yml ,没有解释他们使用.yml扩展名有什么限制。 The recommended extension for YAML files, as posted on the official FAQ on yaml.org , has been .yaml since Sep. 2006. yaml.org官方常见问题解答中发布的YAML文件推荐扩展.yaml自2006年9月起一直是.yaml

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM