Ankita Jain
Ankita Jain

Reputation: 55

Fetch value from json request body and store in a variable in Azure API Management

I want to fetch a value from json and store it in a variable in Azure API Management. JSON Example which is coming in request Body is

{
    "ItemCode": 1,
    "ItemName": "USA",
    "typeCode": "REG"
  }

I need to fetch value of ItemCode and typeCode and store it in a variable.

I have check on Microsoft Docs and all it gives me to transform body by using liquid template which I suppose is of no use in my requirement.

I have stored a JSON in a variable like

set-variable name="varItemCode" value="@(context.Request.Body.As<String>(preserveContent:true))" />

Since this is stored a string I am not able to traverse the JSON Object.

Upvotes: 0

Views: 7981

Answers (2)

Ankita Jain
Ankita Jain

Reputation: 55

I was able to do it

<kbd>set-variable name="varTypeCode" value="@{
                    JObject json = JObject.Parse(context.Variables.GetValueOrDefault<string>("varBody"));
                    var typeCode = json.GetValue("typeCode");
                    return typeCode;
                 }" />

Upvotes: 4

Jayen Chondigara
Jayen Chondigara

Reputation: 485

this is working

 <set-variable name="validationResults" value="@(context.Request.Body.As<JObject>())" />
    
<set-variable name="operation" value="@((string)((JObject)context.Variables["validationResults"])["operation"])" />

Upvotes: 2

Related Questions