Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Collapse uniqe set of JSON objects into one with jq

I have a set of JSON objects that each contain one unique key:value pair (that is, there are no duplicate keys). I want to combine all of these into a single object using jq.

I want this:

{
  "Key1": "Value1"
}
{
  "Key2": "Value2"
}
{
  "Key3": "Value3"
}
...

to become this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": "Value3",
  ...
}

>Solution :

Since this is a single file, use slurp and simply add the objects:

jq -s 'add' yourfile

Output:

{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key3": "Value3"
}

slurp reads all entities in the input file as one big array, which will then be reduced with add. Adding two objects simply merges their key-value pairs, with conflicting keys being overwritten by the last value.

If your input is really really large, you might not want to load all entities into memory at once and you might want to reduce on inputs instead:

jq -n 'reduce inputs as $obj ({}; . + $obj)' yourfile

You might find the question Difference between slurp, null input, and inputs filter helpful.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading