gpt4 book ai didi

arrays - 将任意数量的数组合并为单个数组?

转载 作者:行者123 更新时间:2023-12-04 09:35:42 25 4
gpt4 key购买 nike

我通过 jq 处理了一系列 JSON 文件。 .每个文件由一个字典数组组成,例如

  • file1.json:[{ "id": 1 }]
  • file2.json:[{ "id": 2 }]

  • 我发现将所有输入文件成功合并到一个输出数组的唯一命令是:
    jq --slurp '.[0] + .[1]' file1.json file2.json
    此命令输出 [{ "id": 1 }, { "id": 2 }] ,正如预期的那样。
    我正在编写一个 shell 脚本,它希望将一组可变的文件合并到一个 JSON 数组中作为输出。我的脚本将执行如下内容:
    find . -type f -iname '*.json' | xargs jq 'FILTER'
    这应该调用 jq喜欢 jq 'FILTER' file1.json file2.json ... .
    是否有我缺少的功能可以获取所有输入文件并首先将它们合并到一个连续的对象列表中,而无需将过滤器重写为类似 .[0] + .[1] + .[2] ... 的内容?

    最佳答案

    鉴于:
    1.json

    [{ "id": 1 }]
    2.json
    [{ "id": 2 }]
    3.json
    [{ "id": 3 }]
    然后这个命令:
    jq --slurp 'map(.[])' 1.json 2.json 3.json
    返回:
    [
    {
    "id": 1
    },
    {
    "id": 2
    },
    {
    "id": 3
    }
    ]
    或者干脆:
    jq --slurp 'flatten' 1.json 2.json 3.json

    关于arrays - 将任意数量的数组合并为单个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62603453/

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