Darius
Darius

Reputation: 1149

How to use jq to produce multiple JSON objects?

How would one transform a JSON object into several derived JSON objects with jq?

Example input:

[
  {
     "id": 1,
     "a": "value-in-a",
     "b": "value-in-b"
  },
  {
     "id": 2,
     "c": "value-in-c"
  }
]

Expected output:

[
  {
     "id": "1",
     "value": "value-in-a"
  },
  {
     "id": "1",
     "value": "value-in-b"
  },
  {
     "id": "2",
     "value": "value-in-c"
  }
]

Here the output is an array with 3 elements. First 2 elements are transformed using the first element in the input array. Third element is produced from second element in the input array.

I assume to achieve there will need to be several steps:

a) Construct 2 objects from single JSON object input. Aassume this can be done using variables. First assign input object into variable, then construct object with value a and then with value b. Not sure how to make JQ return several constructed JSON objects.

b) Conditionals will need to be used to not produce an object if a, or b, or c is missing. This can probably be done using 'alternative' operator or if-then-else

Upvotes: 1

Views: 550

Answers (1)

pmf
pmf

Reputation: 36666

You can iterate over the other keys using del and keys_unsorted:

jq 'map({id, value: (del(.id) | .[keys_unsorted[]])})'
[
  {
    "id": 1,
    "value": "value-in-a"
  },
  {
    "id": 1,
    "value": "value-in-b"
  },
  {
    "id": 2,
    "value": "value-in-c"
  }
]

Demo

Upvotes: 3

Related Questions