Veronica
Veronica

Reputation: 133

Format yaml data with hyphen to be written to file typescript

I'm using js-yaml in typescript I need write to a yaml file so that it's formatted like this (notice the hyphen):

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

But I can't figure out how to get the hyphen in front of it when I create the object in typescript so that description, id, and parameters are part of the same object without a unique name for each one. This is what I have so far:

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');

But this creates two separate objects as "data" and "data2", when I want it to just start with "- description". Anyone have any tips?

Upvotes: 1

Views: 907

Answers (1)

Veronica
Veronica

Reputation: 133

Ok I figured it out after playing with it for a while. It needs to be formatted as a set of of key-value pairs as if you were writing to 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');

This way the format comes out with a hyphen in front of description.

Upvotes: 2

Related Questions