JSONata - peek at each element to create/append to an array

77 Views Asked by At

I'd like to transform the following json to the output Input:

{
  "firstName": "Jane",
  "personalHistory": {
    "hadmigraines": true,
    "hadmigraines4InAMonth": true,
    "hadheartDisease": true,
    "hadhighCholesterol": false
  }
}

Output:

{
  "oLifE": {
    "party": [
      {
        "person": {
          "firstName": "Jane"
        },
        "risk": {
          "medicalCondition": [
            {
              "conditionType": "MIGRAINE",
              "numberEpisodesTotal": 4,
              "frequency": "MONTHLY"
            },
            {
              "conditionType": "HEART_DISEASE"
            }
          ]
        }
      }
    ]
  }
}

I need to go through element by element in the personalHistory and add to the output medical array only if the hadxx condition is true. I am struggling with how to create/append to the medicalCondition array, as the person may not have any medical conditions. Please advise.

1

There are 1 best solutions below

0
aeberhart On BEST ANSWER

In order to write the code, you need to specify how the had... keys should be mapped to disease names and frequencies. But this snippet should get you started:

{
  "oLifE": {
    "party": [
      {
        "person": {
          "firstName": firstName
        },
        "risk": {
          /* iterate over each key value pair */
          "medicalCondition": $each(personalHistory, function($v, $k) {
              (
                /* strip had... */
                $k := $substring($k, 3);

                /* parse frequency */
                $parts := $split($k, /[0-9]/);

                $disease := $parts[0];
                $frequency := $parts[1];
                $number := $match($k, /[0-9]/).match;

                /* filter condition = true */
                $v ? {
                    "conditionType": $disease,
                    "numberEpisodesTotal": $number,
                    "frequency": $frequency = "InAMonth" ? "MONTHLY" : undefined
                } : undefined;
              )
            })
        }
      }
    ]
  }
}