cancel
Showing results for 
Search instead for 
Did you mean: 

How to cite entries in an array of JSON (position of entries is not fixed)

shuo
New Contributor

Hi,
Below is just an example JSON:

{
    "entity": {
        "entries": [
            {
                "ID": "1",
                "Pipeline": "Pipeline_Completed",
                "Numbers": "10"
            },
            {
                "ID": "3",
                "Pipeline": "Pipeline_Failed",
                "Numbers": "1"
            },
            {
                "ID": "10",
                "Pipeline": "Pipeline_Stopped",
                "Numbers": "3"
            }
        ],
        "duration": 1074,
        "create_time": "2010-10-10"
    }
}

Constraints: the position of entries is not fixed, Say this time we have pipeline_Failed, so Pipeline_Stopped is the index[2] of the array; but next time if we don’t have pipeline_Failed, then Pipeline_Stopped will have the index[1].

What i did(step1): jsonPath($, "$entity.entries[*].Pipeline").indexOf("Pipeline_Stopped") to retrive the index,
and then use it to get the Numbers(step2):

jsonPath($, "$entity.entries[**jsonPath($, "$entity.entries[*].Pipeline").indexOf("Pipeline_Stopped")**].Numbers")

I replaced the [*] with the index I got from the step 1

But, in the mapper, step2 expression gives me error. How to fix that, or Do we have an alternative way to do this? Also, if there is no Pipeline_Stopped, where indexOf will return -1, will it give error or just null value?(null value is good, just don’t want to get an error in the snap)

Thank you so much!!

2 REPLIES 2

viktor_n
Contributor II

Hi @shuo,

In this situation you can use .find() function.

Here is one simple expression.
Check Null-safe Access in the Mapper.
$entity.entries.find(f => f.get('Pipeline') == 'Pipeline_Failed').Numbers

image

If for example there’s not ‘Pipeline_Failed’ when you validate/execute then will return you a null.

image

Regards,
Viktor

shuo
New Contributor

Hi, Viktor_n,

Thank you for your help, this is a better way!