【问题标题】:Format yaml data with hyphen to be written to file typescript使用连字符格式化 yaml 数据以写入文件打字稿
【发布时间】:2020-10-08 20:51:23
【问题描述】:

我在打字稿中使用js-yaml 我需要写入一个 yaml 文件,以便它的格式如下(注意连字符):

- description: the description
  id: 4265019
  parameters:
    label1: data1
    label2: data2
- description: the description 2
  id: 4265020
  parameters:
    label3: data3
    label4: data4

但是当我在打字稿中创建对象时,我无法弄清楚如何在它前面获取连字符,以便描述、id 和参数是同一对象的一部分 每个对象都没有唯一的名称。这是我目前所拥有的:

let data = { 
    description: "The description",
    id: 4265019,
    parameters: {
        label1: "data1",
        label2: "data2",
    }
};
let data2 = {
    description: "The description 2",
    id: 4265020,
    parameters: {
        label3: "data3",
        label4: "data4",
    }
};
let data3 = {
    data, data2
};

let yamlStr = yaml.safeDump(data3);
fs.writeFileSync(filePath, yamlStr, 'utf8');

但是当我希望它以“-描述”开头时,这会创建两个单独的对象作为“数据”和“数据 2”。有人有什么建议吗?

【问题讨论】:

    标签: javascript typescript visual-studio-code formatting yaml


    【解决方案1】:

    好吧,我玩了一会儿就明白了。它需要被格式化为一组键值对,就像你在写 json 一样:

    let data = 
    [{
        description: "The description",
        id: 4265019,
        parameters: {
            label1: "data1",
            label2: "data2"
        }
    },
    {
        description: "The description 2",
        id: 4265020,
        parameters: {
            label3: "data3",
            label4: "data4"
        }
    }];
    
    // Write to file
    let yamlStr = yaml.safeDump(data);
    fs.writeFileSync(this.changedWordsFile, yamlStr, 'utf8');
    

    这样格式就会在描述前加上一个连字符。

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2013-08-10
      • 2022-07-20
      • 2020-09-10
      • 1970-01-01
      • 2015-12-14
      • 2021-08-24
      • 2018-12-03
      • 2021-01-18
      相关资源
      最近更新 更多