gpt4 book ai didi

json - 将 JSON 哈希中的数组元素替换为其他文件中的内容

转载 作者:行者123 更新时间:2023-12-01 08:03:58 25 4
gpt4 key购买 nike

我有一个配置,内容要与单独文件中的片段交换。我将如何巧妙地实现这一目标?

配置文件可能如下所示:

# 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"
}

要插入的内容(来自单独的文件 的 )作为过时数组元素的替换:
# replacement
{
"stuff": "i want that",
"fancy": "very",
"type": "new"
}

所需的结果应如下所示:
# 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",
}

要求:
  • 内容替换需要根据type键的值。
  • 最好使用 jq和常用的 bash/linux 工具。
  • 数组元素顺序应该保持不变
  • 最佳答案

    jq 解决方案:

    jq --slurpfile repl repl.json '.manipulate=[.manipulate[] 
    | if .type=="replace" then .=$repl[0] else . end]' config.json
  • repl.json - 包含替换 JSON 数据的 json 文件
  • --slurpfile repl repl.json - 读取指定文件中的所有 JSON 文本并将解析的 JSON 值的数组绑定(bind)到给定的全局变量

  • 输出:
    {
    "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"
    }

    关于json - 将 JSON 哈希中的数组元素替换为其他文件中的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46216346/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com