简体   繁体   中英

Joining multiple objects under a single object and adding sibling objects using jq -f .jq

So from what I gather jq does support using -f multiple times. However I'm not sure if this is what I want.

So I have:

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

I was able to merge this object:

owners.json

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

using

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

which contains the jq program

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

as suggested in the reply .

However I'm not sure what to do if I want to merge two additional objects, say I had:

food.json

{
  "food": [
    "meat",
    "fish",
    "vegetables"
  ]
}

as well that I want at the top, resulting in:

{
  "owners": [
    "peter",
    "william",
    "sally"
  ],
  "food": [
    "meat",
    "fish",
    "vegetables"
  ],
  "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"
        }
      ]
    }
  ]
}

Just read in food.json using parameter --slurpfile food food.json and modify program.jq to include it: input as $owners | {$owners, food: $food[0].food, animals: [inputs]} input as $owners | {$owners, food: $food[0].food, animals: [inputs]} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM