0

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": "roney@domain.com",
   "Approver_CC_Email": "tim@domain.com",
   "Customer_CC_Email": "alex@domain.com",   
   "Invoice": "001",
   "Date": "2022-02-14"   
}

Output

{
    "Approver": {
      "email_address": "tim@domain.com",
      "role": "Approver"
    },
    "Customer": {
      "email_address": "alex@domain.com",
      "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:

NJ Bhanushali
  • 901
  • 1
  • 12
  • 21

2 Answers2

1

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": "tim@domain.com",
    "role": "Approver"
  },
  "Customer": {
    "email_address": "alex@domain.com",
    "role": "Customer"
  }
}

Demo

pmf
  • 24,478
  • 2
  • 22
  • 31
1

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);
peak
  • 105,803
  • 17
  • 152
  • 177