我正在尝试使用 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/