How to get object list from key value pairs complex JSON using jq and map? (Active Campaign)

218 Views Asked by At

I have following JSON. I want to get key-value pair objects based on their CC role. In this example there are 3 roles(Presenter, Approver, Customer). Presenter is of type TO. Other 2 are of type CC. I want to get of type CC. There can be more as it is dynamic.

JSON

{
   "Presenter_TO_Email": "[email protected]",
   "Approver_CC_Email": "[email protected]",
   "Customer_CC_Email": "[email protected]",   
   "Invoice": "001",
   "Date": "2022-02-14"   
}

Output

{
    "Approver": {
      "email_address": "[email protected]",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "[email protected]",
      "role": "Customer"
    }
}

I can do using INDEX using this example but as I am using older version of jq, it throws error jq: error: INDEX/2 is not defined at <top-level>, line 1:

2

There are 2 best solutions below

0
pmf On BEST ANSWER

Use with_entries to make changes based on keys and values:

jq '
  with_entries(
    (.key / "_CC_") as $key | select($key[1])
    | {key: $key[0], value: {email_address: .value, role: $key[0]}}
  )
'
{
  "Approver": {
    "email_address": "[email protected]",
    "role": "Approver"
  },
  "Customer": {
    "email_address": "[email protected]",
    "role": "Customer"
  }
}

Demo

0
peak On

In versions of jq which include INDEX/2, it is defined as a simple jq function, so if your jq does not include it, you can simply include its definition yourself:

def INDEX(stream; idx_expr):
  reduce stream as $row ({};
    .[$row|idx_expr|
      if type != "string" then tojson
      else .
      end] |= $row);