Liquid Template - How to map JSON object as a string to output field

54 Views Asked by At

I am new to creating liquid maps in logic app and I'm having some problems mapping a JSON object as a string to a field on the JSON output.

I have this input and I want to map each object as a string to a field on the JSON output, which is also an array.

[
  {
    "firstName": "FirstName1",
    "lastName": "LastName1"
  },
  {
    "firstName": "FirstName2",
    "lastName": "LastName2"
  },
  {
    "firstName": "FirstName3",
    "lastName": "LastName3"
  }
]

I am using this code to create the JSON output.

[
    {%- for rec in content -%}
        {
            "BrokerProperties": {
                "ContentType": "application/json",
                "SessionId": "1"
            },
            "body": "{{ rec }}"
        }
        {% if forloop.last == false %},{% endif %}
    {%- endfor -%}
]

However, when I look at the run history, I see that the body is empty.

Logic App Run History

My expected output is the following. How do I do that?

[
  {
    "BrokerProperties": {
      "ContentType": "application/json",
      "SessionId": "1"
    },
    "body": "{\"firstName\": \"FirstName1\",\"lastName\": \"LastName1\"}"
  },
  {
    "BrokerProperties": {
      "ContentType": "application/json",
      "SessionId": "1"
    },
    "body": "{\"firstName\": \"FirstName2\",\"lastName\": \"LastName2\"}"
  },
  {
    "BrokerProperties": {
      "ContentType": "application/json",
      "SessionId": "1"
    },
    "body": "{\"firstName\": \"FirstName3\",\"lastName\": \"LastName3\"}"
  }
]

I tried updating the liquid map to the following but it still doesn't work.

"body": "{{ rec | json }}"
1

There are 1 best solutions below

2
10p On BEST ANSWER

You don't need to use liquid transformations. The required transformation is trivial enough to be handled by the Select action:

{
  "type": "Select",
  "inputs": {
    "from": "@variables('MyArray')",
    "select": {
      "BrokerProperties": {
        "ContentType": "application/json",
        "SessionId": "1"
      },
      "body": "@{string(item())}"
    }
  },
  "runAfter": {
    "Initialize_variable": [
      "Succeeded"
    ]
  }
}

where the MyArray variable was initialized with your array:

enter image description here

Result:

[
  {
    "BrokerProperties": {
      "ContentType": "application/json",
      "SessionId": "1"
    },
    "body": "{\"firstName\":\"FirstName1\",\"lastName\":\"LastName1\"}"
  },
  {
    "BrokerProperties": {
      "ContentType": "application/json",
      "SessionId": "1"
    },
    "body": "{\"firstName\":\"FirstName2\",\"lastName\":\"LastName2\"}"
  },
  {
    "BrokerProperties": {
      "ContentType": "application/json",
      "SessionId": "1"
    },
    "body": "{\"firstName\":\"FirstName3\",\"lastName\":\"LastName3\"}"
  }
]

enter image description here