Joakin Montesinos
Joakin Montesinos

Reputation: 560

how to parse json with various arrays

I have a json file that looks like:

[
  {
    "id": "aaa",
    "idMembers": [
      "David",
      "Mary"
    ],
    "actions": [
      {
        "id": "1",
        "date": "2019-08-28"
      },
      {
        "id": "2",
        "date": "2019-08-29"
      },
      {
        "id": "3",
        "date": "2019-08-30"
      }
    ]
  },
  {
    "id": "bbb",
    "idMembers": [
      "Mar",
      "Alex"
    ],
    "actions": [
      {
        "id": "1",
        "date": "2019-07-28"
      },
      {
        "id": "2",
        "date": "2019-07-29"
      }
    ]
  }
]

I would like to obtain a result like:

["David", "Mary", "1", "2019-08-28"]
["David", "Mary", "2", "2019-08-29"]
["David", "Mary", "3", "2019-08-30"]
["Mar", "Alex", "1", "2019-07-28"]
["Mar", "Alex", "2", "2019-07-29"]

I tried:

jq -c '.[] | [ .idMembers[], .actions[].id, .actions[].date] '

But results are:

["David", "Mary", "1", "2", "3", "2019-08-28", "2019-08-29", "2019-08-30"]
["Mar", "Alex", "1", "2", "2019-07-28", "2019-07-29"]

I would like do someting like:

jq -c '.[] | .idMembers[], .actions[] | [ .id, .date] '

but it return me

jq: error (at :1268): Cannot index string with string "id"

Is possible to do something similar to this?

jq -c '.[] | .actions[] | [.idMembers[], .id, .date] '

Upvotes: 2

Views: 116

Answers (1)

oguz ismail
oguz ismail

Reputation: 50750

Make an array out of each object under actions and add it to idMembers.

.[] | .idMembers + (.actions[] | map(.))

map(.) can also be written as [.[]]. For clarification, above is the same as:

.[] | .idMembers + (.actions[0] | map(.)),
      .idMembers + (.actions[1] | map(.)),
      .idMembers + (.actions[2] | map(.)),
                            ...
      .idMembers + (.actions[n] | map(.))

where n is the number of elements in actions.

Upvotes: 3

Related Questions