在一个命令中合并单个对象下的多个对象和添加同级对象 [英] Merge multiple objects under a single object and add sibling object in one command

查看:3
本文介绍了在一个命令中合并单个对象下的多个对象和添加同级对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有三个文件:

cats.json

{
  "cats": [
    {
      "name": "fluffles",
      "age": 10,
      "color": "white"
    }
  ]
}

dogs.json

{
  "dogs": [
    {
      "name": "sam",
      "age": 5,
      "color": "black and white"
    },
    {
      "name": "rover",
      "age": 2,
      "color": "brown and white"
    }
  ]
}

Snakes.json

{
  "snakes": [
    {
      "name": "noodles",
      "age": 10,
      "color": "green"
    }
  ]
}

我想将它们合并在一起,放在一个动物对象下。我发现这将合并文件:

jq -s '{"animals": .} ' cats.json dogs.json snakes.json > animals.json
{
  "animals": [
    {
      "cats": [
        {
          "name": "fluffles",
          "age": 10,
          "color": "white"
        }
      ]
    },
    {
      "dogs": [
        {
          "name": "sam",
          "age": 5,
          "color": "black and white"
        },
        {
          "name": "rover",
          "age": 2,
          "color": "brown and white"
        }
      ]
    },
    {
      "snakes": [
        {
          "name": "noodles",
          "age": 10,
          "color": "green"
        }
      ]
    }
  ]
}

现在我有一个额外的对象:

owners.json

{
  "owners": [
    "peter",
    "william",
    "sally"
  ]
}

我要使用

将其合并到同一文件中
jq -s '.[0] + .[1]' animals.json owners.json

我可以用一个jq命令同时执行这两个操作吗?

jq -s '{"animals": .} ' cats.json dogs.json snakes.json > animals.json
jq -s '.[0] + .[1]' animals.json owners.json

结果如下:

{
  "animals": [
    {
      "cats": [
        {
          "name": "fluffles",
          "age": 10,
          "color": "white"
        }
      ]
    },
    {
      "dogs": [
        {
          "name": "sam",
          "age": 5,
          "color": "black and white"
        },
        {
          "name": "rover",
          "age": 2,
          "color": "brown and white"
        }
      ]
    },
    {
      "snakes": [
        {
          "name": "noodles",
          "age": 10,
          "color": "green"
        }
      ]
    }
  ],
  "owners": [
    "peter",
    "william",
    "sally"
  ]
}

推荐答案

假设您有一个(先验的)不确定或大量的动物类型,并且只有一个owners文件。在这种情况下,不使用-s选项会更好(节省内存),并且使用所有者文件作为第一个数据文件来调用JQ会更容易,例如

jq -n -f program.jq owners.json $(ls *.json | grep -v owners.json)

其中Program.jq包含程序,例如:

input as $owners | {$owners, animals: [inputs]}

(请注意{"owners": $owners}如何缩写。)

这篇关于在一个命令中合并单个对象下的多个对象和添加同级对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆