Merge JSON Arrays

So my goal is to combine json files in this format:

{
  "title": "NamesBook",
  "list": [
    {
      "name": "Ajay"
    },
    {
      "name": "Al"
    }
  ]
}

And I have files that look like this:

blahblah.json

{
  "title": "NamesBook",
  "list": [
    {
      "name": "Ajay"
    }
  ]
}

blueblue.json

{
  "title": "NamesBook",
  "list": [
    {
      "name": "Al"
    }
  ]
}

I can save an array of a list of all my names in a variable with the following:

x = jq -s '.[].list' *.json

And then I planned to add the variable to an empty array in the out.json file I created, which looks like this:

{
  "type": "NamesBook",
  "list": []
}

However, when my script runs through the line

jq '.list[] += "$x"' out.json'

It raises a jq error:

Unable to iterate over zero.

Even when I add a random item, the same error appears. Tips on how I should act? Are there other tools in jq to help achieve array merging?

+4
source share
3 answers

add (jq 1.3 +):

jq -s '.[0].list=[.[].list|add]|.[0]' *.json

(jq 1,5 +):

jq -s '.[0].list=([.[].list]|flatten)|.[0]' *.json

[.[].list] - "list"

 [
  [
    {
      "name": "Ajay"
    }
  ],
  [
    {
      "name": "Al"
    }
  ]
]

[.[].list]|flatten - ( .[].list|add - )

[
  {
    "name": "Ajay"
  },
  {
    "name": "Al"
  }
]

.[0].list=([.[].list]|flatten)|.[0] - "" , .

{
  "title": "NamesBook",
  "list": [
    {
      "name": "Ajay"
    },
    {
      "name": "Al"
    }
  ]
}
+4

, title, list, :

$ jq 'reduce inputs as $i (.; .list += $i.list)' blahblah.json blueblue.json

.

+2

OP , , , .title "NamesBook". .title, "NamesBook", :

map(select(.title == "NamesBook"))
| {title: .[0].title, list: map( .list ) | add}

, jq -s.

, add - : .

+1

Source: https://habr.com/ru/post/1668664/


All Articles