'Edit yaml files using js function

I am trying to edit a template-yaml file using a js function. The js function will get a name of organization: org and this will replace corresponding values in the template-yaml and generate a org-yaml.

My template-yaml file looks like this:

Organizations:
    - &Org3   # this line here is important.
        Name: Org3Name
        ID: Org3ID

I am using the below function:

const yaml = require('js-yaml');
const fs = require('fs');

const changeConfig = (org) => {
    // doc.Organizations[0] = org;
    doc.Organizations[0].Name = org + 'Name';
    doc.Organizations[0].ID = org + 'ID';
    fs.writeFileSync('new_file.yaml', yaml.dump(doc));
}

let doc = yaml.load(fs.readFileSync('./sample_yaml.yaml', 'utf-8'));
changeConfig('Org1');

I am getting is this:

Organizations:
  - Name: Org1MSP
    ID: Org1MSP

Is there some way I can modify to get a structure like this:

Organizations:
  - Org1  # notice this
    Name: Org1MSP
    ID: Org1MSP


Solution 1:[1]

Kalinda, you can try this:

const yaml = require('js-yaml');
const fs = require('fs');

const changeConfig = (org) => {
    doc.Organizations[0][org] = {};
    delete doc.Organizations[0].Org;
    doc.Organizations[0][org].Name = org + 'Name';
    doc.Organizations[0][org].ID = org + 'ID';
    fs.writeFileSync('new_file.yaml', yaml.dump(doc));
}

let doc = yaml.load(fs.readFileSync('./sample_yaml.yaml', 'utf-8'));
changeConfig('Org2');

Sample yaml file:

Organizations:
    - Org:
        Name: OrgName
        ID: OrgID

if is correct, you need rename or create a new key in yaml file.

Result:

Organizations:
  - Org2:
      Name: Org2Name
      ID: Org2ID

When you use load methods, this methods transform your yaml file in plain object. So you can have better control over your object within javascript.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jradelmo