Home > Software engineering >  Joining multiple objects under a single object and adding sibling objects using jq -f .jq
Joining multiple objects under a single object and adding sibling objects using jq -f .jq

Time:10-14

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

CodePudding user response:

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

  • Related