jq expression to merge

I have the below JSON document from the Junos REST API. I am trying to simplify the document down to just a select few items. How would I accomplish this?

Expected JSON:

[
  {  "status": .member-status[0].data,
     "serial": .member-serial-number[0].data,
     "slot": .fpc-slot[0].data
  },
  ...
] 

Original JSON:

{
  "member-status": [
    {
      "data": "Prsnt"
    }
  ],
  "member-id": [
    {
      "data": "0"
    }
  ],
  "fpc-slot": [
    {
      "data": "(FPC 0)"
    }
  ],
  "member-serial-number": [
    {
      "data": "serNo1"
    }
  ],
  "member-model": [
    {
      "data": "ex4400-24t"
    }
  ],
  "member-priority": [
    {
      "data": "255"
    }
  ],
  "member-mixed-mode": [
    {
      "data": "N"
    }
  ],
  "member-route-mode": [
    {
      "data": "VC"
    }
  ],
  "member-role": [
    {
      "data": "Master*"
    }
  ],
  "neighbor-list": [
    {}
  ]
}
{
  "member-status": [
    {
      "data": "NotPrsnt"
    }
  ],
  "member-id": [
    {
      "data": "1"
    }
  ],
  "fpc-slot": [
    {
      "data": "(FPC 1)"
    }
  ],
  "member-serial-number": [
    {
      "data": "serNo2"
    }
  ],
  "member-model": [
    {}
  ]
}
Asked By: verideskstar

||

Should be something like:

jq -s '
  map(
    {
      "status": ."member-status"[0].data,
      "serial": ."member-serial-number"[0].data,
      "slot"  : ."fpc-slot"[0].data
    }
  )' your-file.json

Or factorising code a little:

jq -s '
  map({
    "status": ."member-status",
    "serial": ."member-serial-number",
    "slot"  : ."fpc-slot"
  } | with_entries(.value |= .[0].data))' your-file.json

Or as your simplified key for all three happen to be the second --separated word:

jq -s '
  map({"member-status", "member-serial-number", "fpc-slot"} |
  with_entries(.value |= .[0].data | .key |= split("-")[1]))' your-file.json

Which on your sample gives:

[
  {
    "status": "Prsnt",
    "serial": "serNo1",
    "slot": "(FPC 0)"
  },
  {
    "status": "NotPrsnt",
    "serial": "serNo2",
    "slot": "(FPC 1)"
  }
]

-s slurps the several concatenated JSONs in the input into one JSON array, and map() maps the specified object to each member. As an alternative to map({...}), you could also do [ .[] | {...} ] which iterates over the array members and builds a new array out of the result.

Answered By: Stéphane Chazelas
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.