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

Time:02-22

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:

CodePudding user response:

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

  • Related