PrimroseBank
PrimroseBank

Reputation: 41

APIM Policy example for extracting a specific item from a JSON array response

I have a JSON array response that returns values similar to:

[
    {
        "code": "SCH",
        "title": "School Email",
        "emailType": "school",
        "id": "123455"
    },
    {
        "code": "PER",
        "title": "Personal Email",
        "emailType": "personal",
        "id": "123456"
    }
]

In my APIM policy I want to match on an incoming code e.g. "PER" and store corresponding id result in the cache. I've tried lots of variants of the following policy to extract a single value:

<set-variable name="emailId" 
value="@{var emailTypes = JArray.Parse(context.Variables["emailTypesList"].ToString());     
                    var emailId = emailTypes.FirstOrDefault(x => x["code"].Value<string>() == "PER");                
                    return emailId?["id"]?.ToString();
                    }"/>

but I'm having trouble getting the syntax correct and am getting "Error in element 'set-variable' on line 25, column 18: Usage of member '' of type 'System.Object' is not supported within expressions". Can anyone provide me with a way to do this? Is it possible or is it not possible because I'm using a JArray (Object)?

I've read that there are only certain variable types available in the policies but it seems objects can be used within the C# code block (or is this not correct)?

Any tips appreciated, thanks in advance

Upvotes: 0

Views: 267

Answers (1)

10p
10p

Reputation: 6686

If you want to get the id for the code == "PER" from your JSON array response, here is the code:

<set-variable name="emailId" value="@{
    var jsonArray = JArray.Parse(context.Response.Body.As<string>());
    var id = jsonArray.FirstOrDefault(x => x["code"].ToString() == "PER")?["id"].ToString();
    return id;
}" />

Upvotes: 1

Related Questions