如何在 Node.js 中解析 YAML 文件

How can I parse a YAML file in Node.js

我目前正在尝试用当前内容解析 Ansible hosts.yaml 文件

all:
  masters:
    master_1: 
      ansible_host: ""
      image: ""
  workers:
    worker_1:
      ansible_host: ""
      image: ""
    worker_2:
      ansible_host: ""
      image: ""

在带有库'js-yaml'的nodeJS中,但它创建的对象是

{
  all: {
    masters: { 
      master_1: {
        ansible_host: ""
        image: ""
      }
    },
    workers: { 
      worker_1: {
        ansible_host: ""
        image: ""
      }, 
      worker_2: {
        ansible_host: ""
        image: ""
      } 
    }
  }
}

这个问题是能够遍历 masters/workers 主机。我希望它是一个像

这样的数组
{
  all: {
    masters: [ 
      { master_1: {
          ansible_host: ""
          image: ""
        }
      },
      {...}...
    ],
    workers: [ 
      {...},
      {...}...
    ]
  }
}

或类似的东西,我可以在其中获取主机的数量并读取主机的变量。我还需要将它保存回 hosts.yaml 以便 ansible 使用而不会出错。有什么东西不见了吗?这不可能吗?

YAML 到 JSON 的解析是正确的。 如果你打算读取workermaster主机的值,你仍然可以通过以下方式进行:

const hosts = {
  all: {
    masters: { 
      master_1: {
        ansible_host: "m1",
        image: "m1_image"
      }
    },
    workers: { 
      worker_1: {
        ansible_host: "w1",
        image: "w1_image"
      }, 
      worker_2: {
        ansible_host: "w2",
        image: "w2_image"
      } 
    }
  }
};

const { masters, workers } = hosts.all;
const masterHosts = Object.keys(masters);
const workerHosts = Object.keys(workers);

// printing their lengths
console.log('masters', masterHosts.length);
console.log('workers', workerHosts.length);

// printing worker hosts
masterHosts.forEach(masterId => {
 console.log(masters[masterId].ansible_host);
  console.log(masters[masterId].image);
})

// printing worker hosts
workerHosts.forEach(worker => {
  console.log(workers[worker].ansible_host);
  console.log(workers[worker].image);
  // uupdating the hosts.
  workers[worker].ansible_host += '_updated';
});

console.log(hosts)