我有一个配置,内容可以与来自单独文件的片段进行交换。我将如何巧妙地实现这一目标?
配置文件可能如下所示:
# config file
{
"keep": "whatever type of value",
"manipulate": [
{
"foo": "bar",
"cat": {
"color": "grey"
},
"type": "keep",
"detail": "keep whole array element"
},
{
"stuff": "obsolete",
"more_stuff": "obsolete",
"type": "replace",
"detail": "replace whole array element with content from separate file"
},
{
"foz": "baz",
"dog": {
"color": "brown"
},
"type": "keep",
"detail": "keep whole array element"
},
],
"also_keep": "whatever type of value"
}
Run Code Online (Sandbox Code Playgroud)
要插入以替换过时数组元素的内容(来自单独的文件):
# replacement
{
"stuff": "i want that",
"fancy": "very",
"type": "new"
}
Run Code Online (Sandbox Code Playgroud)
所需的结果应如下所示:
# result
{
"keep": "whatever kind of value",
"manipulate": [
{
"foo": "bar",
"cat": {
"color": "grey"
},
"type": "keep",
"detail": "keep whole array element"
},
{
"stuff": "i want that",
"fancy": "very",
"type": "new"
},
{
"foz": "baz",
"dog": {
"color": "brown"
},
"type": "keep",
"detail": "keep whole array element"
},
],
"also_keep": "whatever kind of value",
}
Run Code Online (Sandbox Code Playgroud)
要求:
type键的值来完成。jq和常用的 bash/linux 工具。jq解决方案:
jq --slurpfile repl repl.json '.manipulate=[.manipulate[]
| if .type=="replace" then .=$repl[0] else . end]' config.json
Run Code Online (Sandbox Code Playgroud)
repl.json- 包含替换 JSON 数据的 json 文件
--slurpfile repl repl.json- 读取指定文件中的所有 JSON 文本,并将已解析 JSON 值的数组绑定到给定的全局变量
输出:
{
"keep": "whatever type of value",
"manipulate": [
{
"foo": "bar",
"cat": {
"color": "grey"
},
"type": "keep",
"detail": "keep whole array element"
},
{
"stuff": "i want that",
"fancy": "very",
"type": "new"
},
{
"foz": "baz",
"dog": {
"color": "brown"
},
"type": "keep",
"detail": "keep whole array element"
}
],
"also_keep": "whatever type of value"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1752 次 |
| 最近记录: |