我正在使用 https://github.com/nodeca/js-yaml 将 json 文件转换为 YAML 文件使用安全转储
结果是这样的
en:
models:
errors:
name: name not found
url: bad url
user:
errors:
name: name not found
url: bad url
photo:
errors:
name: name not found
url: bad url
但我想要一个脚本来压缩引用
en:
models:
errors: &1
name: name not found
url: bad url
user:
errors: *1
photo:
errors: *1
最佳答案
基于 Anthon 中的 Python 脚本https://stackoverflow.com/a/55808583/10103951
function buildRefsJson(inputJson, mappings = null) {
if (!mappings) {
mappings = {}
}
if (typeof(inputJson) === 'object') {
let value
let stringValue
let ref
for (let key in inputJson) {
value = inputJson[key]
stringValue = JSON.stringify(value)
ref = mappings[stringValue]
if (ref) {
inputJson[key] = ref
} else {
mappings[stringValue] = value
buildRefsJson(inputJson[key], mappings)
}
}
}
我将其转换为 JavaScript 代码。它完成了工作!也感谢 Niroj帮助
关于javascript - 如何使用脚本中的引用压缩 YAML 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55807446/