How to find element in the array, by comparing id with the referenced id in another array element

73 views Asked by At

In my data model I have three arrays:

  • risk_areas
  • risks
  • indicators

Elements for the risks array referencing to elements of risk_area array and elements of indicators array referencing to elements for the risks array. So to find a risks score for "Pandemic outbreaks" with the specific risk_area "Delivery", I need to pass risk_area id into the risk_area_id of the risks element.

The question is: How can I achieve it by using the JSON path?

I'm using Java and com.jayway.jsonpath:json-path:2.7.0 library.

My code was:

data.attributes.risks[?(@.name == 'Pandemic outbreaks' && @.risk_area_id == $.data.attributes.risk_areas[?(@.name == 'Delivery')].id)].score.value

But unfortunately it does not work for me.

Separately it works fine, but not in combination:

data.attributes.risks[?(@.name == 'Pandemic outbreaks' && @.risk_area_id == '4620c0d7-e34a-4988-b3d2-798270f3053e')].score.value
$.data.attributes.risk_areas[?(@.name == 'Delivery')].id
{
  "data": {
    "id": "string",
    "type": "score_card",
    "attributes": {
      "score": {
        "available": true,
        "value": 80
      },
      "risk_areas": [
        {
          "type": "risk_area",
          "id": "4620c0d7-e34a-4988-b3d2-798270f3053e",
          "name": "Delivery",
          "score": {
            "available": true,
            "value": 80
          }
        }
      ],
      "risks": [
        {
          "type": "risk",
          "id": "04215735-dfe7-48d0-8139-8ead770cf362",
          "name": "Pandemic outbreaks",
          "risk_area_id": "4620c0d7-e34a-4988-b3d2-798270f3053e",
          "score": {
            "available": true,
            "value": 70
          }
        }
      ],
      "indicators": [
        {
          "id": "RM0001",
          "type": "indicator",
          "name": "Pandemic disease outbreak",
          "indicator_message_id": "0b5cd4d1-5145-411b-a979-f2b8722a9f57",
          "frozen": true,
          "ko": true,
          "risk_id": "04215735-dfe7-48d0-8139-8ead770cf362",
          "score": {
            "available": true,
            "value": 80
          }
        }
      ]
    }
  }
}
1

There are 1 answers

0
Raymond Choi On

You may consider another JSON library Josson. It can query the data in one simple statement.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(jsonString);
Integer value = josson.getInteger(
    "data.attributes.risks[name='Pandemic outbreaks' & risk_area_id=..risk_areas[name='Delivery'].id].score.value");
System.out.println(value);

Output

70