APIM Liquid template - context.Variables access content as JSON

GFPhillips 1 Reputation point
2020-06-08T07:02:54.017+00:00

Hi All,

this is roughly the policy i have in place

<policies>
    <inbound>
        <send-request mode="new" response-variable-name="response">
            <!-- Calling external service and getting JSON response back-->
        </send-request>
        <choose>
            <when condition="@(((IResponse)context.Variables["response"]).StatusCode == 200)">
                <set-variable name="myvariable" value="@(((IResponse)context.Variables["response"]).Body.As<string>())" />
                </when>
            </choose>
            <otherwise>
                <!-- Do some other stuff-->
            </otherwise>
            <base />
        </inbound>
        <backend />
        <outbound>
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body template="liquid">
                <!-- PROBLEM: How do I access the variable as a json if i cant parse it on my template -->
              {{context.Variables["myvariable"]}}
            </set-body>
            <base />
        </outbound>
        <on-error>
            <base />
        </on-error>
    </policies>

How can i access context.Variables["myvariable"] as json on my liquid template? - This is currently a JSON string

Thanks

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,771 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Pramod Valavala 20,591 Reputation points Microsoft Employee
    2020-07-16T16:20:15.74+00:00

    There doesn't seem to be any filter present in liquid or its C# implementation, DotLiquid that allows for parsing JSON strings. But here is a workaround that I can confirm works

    12754-image.png

    12658-apim-liquid-json-parse-policy-sample.txt

    1 person found this answer helpful.
    0 comments No comments

  2. Oscar Garcia @ozkary 1 Reputation point
    2022-03-22T23:05:53.487+00:00

    An approach is to save the variable as an object instead. This should persist the JSON document

     <set-variable name="myvariable" value="@(((IResponse)context.Variables["response"]).Body.As<JObject>())" />
    
    0 comments No comments