Chris Halcrow
Chris Halcrow

Reputation: 32050

Liquid transform - how to retain JSON object literal unchanged

I have JSON that looks like this:

[
    {
        "Data": {
            "BagData": null,
            "OtherData": {
                "Responses": [
                    "test"
                ]
            }
        }
    },
    {
        "Data": {
            "BagData": {
                "BagWeight": 20.0,
                "ExceededBy": 0.0
            },
            "OtherData": null
        }
    }
]

I'm trying to transform this using a Liquid template. I want to simply output the JSON object literal for "Data" unchanged, but using a different property name so that the output is:

[
    {
        "MessageDetails": {
            "BagData": null,
            "OtherData": {
                "Responses": [
                    "test"
                ]
            }
        }
    },
    {
        "MessageDetails": {
            "BagData": {
                "BagWeight": 20.0,
                "ExceededBy": 0.0
            },
            "OtherData": null
        }
    }
]

I'm using the following Liquid transform template, however it's outputting nothing in place of transaction.Data (content definitely contains the correct array of JSON object literals)

[
    {% for transaction in content %}
      {
        "MessageDetails": {{ transaction.Data }},

      },
    {% endfor %}
]

How do I output the value of "Data" unchanged? I want it to work even if the structure for the value of "Data" changes. So, if the value of "Data" is:

{
  "SomethingCompletelyDifferent": null
}

I still want that to appear in the output, so that the final output would be:

[
    {
        "MessageDetails" : {
            "SomethingCompletelyDifferent": null
        }
    },
    ...
]

Upvotes: 1

Views: 1022

Answers (1)

Lyderies
Lyderies

Reputation: 53

Have you tried breaking the JSON down further so it is more specific?

{% for transaction in content %}
      {
         "MessageDetails": {
            "BagData": {
                "BagWeight": {{transaction.MessageDetails.BagData.BagWeight}},
                "ExceededBy": {{transaction.MessageDetails.BagData.ExceededBy}}
            },
            "OtherData": {{transaction.MessageDetails.OtherData}}
        }
      },
{% endfor %}

When writing out the template I find that you need to be specific on how you want it to look. Writing out each key and then calling its value allows you to template the JSON exactly how you want it too.

The for loop maps through each object it has received and will create what you have templated per object.

Upvotes: 0

Related Questions