1

The problem: I have N numbers of arrays of objects with the same identifying key within objects, and I'd love to merge those with jq.

This is a contrived example that attempts to illustrate the problem:

From

[
  {
    "google.com": {
      "http": {
        "dest_url": "http://stackoverflow.com"
      }
    }
  },
  {
    "google.com": {
      "https": {
        "dest_url": "https://github.com"
      }
    }
  },
  {
    "test.com": {
      "https": {
        "dest_url": "https://wikipedia.com"
      }
    }
  }
]

To

{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.com"
    },
    "https": {
      "dest_url": "https://github.com"
    }
  },
  "test.com": {
    "https": {
      "dest_url": "https://wikipedia.com"
    }
  }
}

I tried with jq '. | add' file but it ended up with the following result.

{
  "google.com": {
    "https": {
      "dest_url": "https://github.com"
    }
  },
  "test.com": {
    "https": {
      "dest_url": "https://wikipedia.com"
    }
  }
}

2 Answers 2

2

A shorter alternative using reduce and recursive merging by * operator:

reduce .[] as $p ({}; . * $p)

demo at jqplay.org

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the group_by() of the keyname after doing to_entries() and form the final JSON from the grouped result

map(to_entries[])
| group_by(.key)[] 
| { (.[0].key) : map(.value)|add }

See it working on jq-play

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.