-2

Hi I have below code which has individual key:value maps needs to be merged into a single key:value map

From below code

{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
}
{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
}

To below code using jq

{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
},
{
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
}
NKRSHNA
  • 15
  • 8
  • 1
    Both `from` and `to` are exactly the same? If you [edit] your question to fix that, please add your attempts. – 0stone0 Jul 04 '23 at 16:09
  • 1
    Adding a comma renders it invalid JSON. That seems unwise. Did you mean you want to convert the input stream into a single JSON array? – peak Jul 04 '23 at 16:44
  • yes, convert individual key:value maps into a single JSON array – NKRSHNA Jul 05 '23 at 10:02
  • 1
    Does this answer your question? [How to combine the sequence of objects in jq into one object?](https://stackoverflow.com/questions/34477547/how-to-combine-the-sequence-of-objects-in-jq-into-one-object) – 0stone0 Jul 05 '23 at 15:39

1 Answers1

0

I cannot find the dupe, so here goes.

To add each file as element into one big array, you can use -s/--slurp with the identity filter .:

jq -s '.' file1.json file2.json

… or collect inputs into an array (with -n/--null-input):

jq -n '[inputs]' file1.json file2.json

or without -n:

jq '[., inputs]' file1.json file2.json

You can read more about the differences of slurping vs consuming inputs in Difference between slurp, null input, and inputs filter

Output:

[
  {
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
  },
  {
    "Key1": "value1",
    "Key2": "value2",
    "Key3": "value3",
    "Key4": "value4"
  }
]
knittl
  • 246,190
  • 53
  • 318
  • 364