javascript - 使用 $ 和 { 时将 JSON 解析为 YAML 失败

标签 javascript node.js json yaml

我正在尝试使用 js-yaml 将 JSON 转换为 YAML,但我似乎无法正确解析我的集合。 考虑以下代码:

function callBackFunc(require,module,exports) {
const yaml = require('js-yaml')

const content = {
  stages: {
    jobs: [{
        scripts: [
          '/opt/scripts/git/git-repository-information-restore.sh',
          'cp ${bamboo.gitconfig_path} ${bamboo.build.working.directory}',
          'cp ${bamboo.npmrc_path} ${bamboo.build.working.directory}',
          'cp ${bamboo.gitcredentials_path} ${bamboo.build.working.directory}',
          'docker build --build-arg VERSION=patch --build-arg REPO=${bamboo.planRepository.repositoryUrl} --no-cache .',
          '/opt/scripts/docker/stop-docker-containers.sh'
        ]
      },
      {
        requirements: 'REMOTE_ONLY'
      }
    ]
  }
}
console.log(yaml.safeDump(content))
}

$.getScript( "https://pastebin.com/raw/PcCb27LS", function( data, textStatus, jqxhr ) {});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

它返回:

stages:
  jobs:
    - scripts:
        - /opt/scripts/git/git-repository-information-restore.sh
        - 'cp ${bamboo.gitconfig_path} ${bamboo.build.working.directory}'
        - 'cp ${bamboo.npmrc_path} ${bamboo.build.working.directory}'
        - 'cp ${bamboo.gitcredentials_path} ${bamboo.build.working.directory}'
        - >-
      docker build --build-arg VERSION=patch --build-arg
      REPO=${bamboo.planRepository.repositoryUrl} --no-cache .
        - /opt/scripts/docker/stop-docker-containers.sh
    - requirements: REMOTE_ONLY

出于某种我不知道的原因,脚本 Node 被 ' 包围,并且 >- 被插入。 知道我做错了什么吗?

提前致谢。 问候

最佳答案

这里有两个问题:

  • 在 docker 构建行中插入换行符 (>)。
  • 脚本 Node 被引用(')

第一个很容易修复,我们可以告诉 js-yaml 增加最大线宽,如下所示:

const options = { lineWidth: 1000 };
console.log(yaml.safeDump(content, options));

第二个更困难,js-yaml 引用脚本行的原因是它们包含大括号字符,必须在 Yaml 中引用。输出仍然有效,因此也许一旦清楚了为什么要引用字符串,就不会有真正的问题了!

关于javascript - 使用 $ 和 { 时将 JSON 解析为 YAML 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56965469/

相关文章:

javascript - 添加到 chrome devtools 中的设置

javascript - Ajax:将代码注入(inject) Internet Explorer

javascript - 使用 javascript 添加总数

javascript - Node findById() 仅因无效 ID 而崩溃 : Cast to ObjectId failed for value

node.js - 除非 Passport.js 被初始化,否则 session ID 不会持续存在

java - 无法将 JSON 十六进制颜色转换为 Java 字符串或 java.awt.Color

javascript - 减少条件未定义的返回

Node.js 和 node-oracle : Problems connecting to Oracle database

json - AWS API 网关模型 : Invalid model schema specified

javascript - 如何将一个对象内部的值数组分组到另一个对象数组