[SalesForce] Using GTL to Display Data from Nested JSON Arrays

I am building an email using data passed through JSON. Here is an example of the JSON file:

{
  "order": {
    "items": [
      {
        *Other Data*,
        "tracking": [
          {
          **"number": "8768123231",
          "url": "website.com"**
          },
          {
          **"number": "1234324234",
          "url": "website.com"**
          }
        ]
      },
      {
        *Other Data*,
        "tracking": [
          {
          **"number": "987123123",
          "url": "website.com"**
          }
        ]
      }
    ]
  }
}

The data I need to access if the tracking numbers. I was able to loop through the different items in the JSON by using SSJS and GTL like this:

<script runat=server>
    function set(key, val) {
      var newVal = val != null ? Stringify(val) : "{}";
      Variable.SetValue(key, newVal);
    }
    Platform.Load("Core","1");
    var Json = Variable.GetValue("@Json");
    var _JsonObject = Platform.Function.ParseJSON(Json);
    set("@items", _JsonObject.order.items);
</script>

+

{{.dataobject items type=variable}}
    {{.data}}
        {"target":"@items"}
    {{/data}}
{{/dataobject}}
{{#each items}}
    *Print Out Item Details*
{{/each}}

Given the unknown number of items and tracking numbers associated with those items, I think the only way to make it work is to have an each loop for the tracking numbers within the items each loop.

Something like this:

{{.dataobject items type=variable}}
    {{.data}}
        {"target":"@items"}
    {{/data}}
{{/dataobject}}
{{#each items}}
    *Print Out Item Details*
    {{.dataobject tracking type=variable}}
        {{.data}}
            {"target":".this.tracking"}
        {{/data}}
    {{/dataobject}}
    {{#each tracking}}
        *Print Out Tracking Number*
    {{/each}}
{{/each}}

But obviously, I can't figure out how to get something like that to work. I'm not sure if what I'm trying to do is even possible so any guidance or advice would be appreciated.

Best Answer

I managed to find a solution here under Nested Datasource Example: https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-programmatic-content.meta/mc-programmatic-content/gtlDatasourceTagExamples.htm

I literally copy/paste the example and got a working version. You can nest the GTL to loop again through your tracking numbers.

Hope this helps!

Related Topic