繁体   English   中英

使用参考属性将 JSON 转换为 YAML

[英]Convert JSON to YAML with reference properties

我正在构建一个用于配置 YAML 文件的 Web 界面,因此需要将 YAML 解析为 JSON 并返回到 YAML。 节点模块 yaml-js 在将我的 YAML 转换为 JSON 方面做得非常好,但是当我转换回 YAML 时,文件最终会变得很大并且不是人类可读的,因为重复项没有保存为锚点和引用。 难道我做错了什么?

这是我想要实现的最小版本:

const yaml = require("js-yaml");

const json = {
  constants: {
    person: {
      name: "july",
      id: 2
    }
  },
  worldObject: {
    name: "july",
    id: 2
  },
  worldArray: [
    {
      name: "july",
      id: 2
    },
    {
      name: "july",
      id: 2
    }
  ]
};

const jsonToYaml = async () => {
  const output = yaml.safeDump(json);
  console.log(output);
};

jsonToYaml();

预期输出

constants:
    person: &person 
        name: july
    id: 2
worldObject: *person
worldArray:
- *person
- *person

替代方案: https : //codesandbox.io/s/small-pine-0w4ze?file=/ src/ index.js

非常感谢提前! 提奥

在您的示例中,源 JavaScript 对象(不是 JSON)没有引用的概念。 您不是在转换带有嵌套引用的 JavaScript 对象。 只要您的底层 JavaScript 对象有引用,您就只能使用 YAML 引用。

这是一个提供预期输出的示例:

const yaml = require("js-yaml");

const person = {
  name: "july",
  id: 2
};

const obj = {
  constants: {
    person: person
  },
  worldObject: person,
  worldArray: [
    person,
    person
  ]
};

const jsonToYaml = async () => {
  const output = yaml.safeDump(obj);
  console.log(output);
};

jsonToYaml();

输出

constants:
  person: &ref_0
    name: july
    id: 2
worldObject: *ref_0
worldArray:
  - *ref_0
  - *ref_0

当严格地从 JSON 转移到 YAML 时,您失去了引用的概念。

对于展开的对象,您可以为noRefs传递true

const output = yaml.safeDump(obj, { noRefs: true });

一个实际的 JSON 示例

正如您在下面的示例中看到的,我使用的是实际的 JSON。 如上所述,一旦您将 JSON 反序列化为一个对象,您实际上就没有引用了。

const yaml = require("js-yaml");

const jsonStr = `{
  "constants": {
    "person": {
      "name": "july",
      "id": 2
    }
  },
  "worldObject": {
    "name": "july",
    "id": 2
  },
  "worldArray": [ {
    "name": "july",
    "id": 2
  }, {
    "name": "july",
    "id": 2
  } ]
}`;

const jsonToYaml = async () => {
  console.log(yaml.safeDump(JSON.parse(jsonStr)));
};

jsonToYaml();

暂无
暂无

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

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