[SalesForce] Looping through json in email – impossible

This nested Guide Template Language snippet
brings me 6 rows of titles.
Problem: I have a complex layout in an email and I want to
populate it with titles in different places.

I can not make a simple design, like a list, to loop and populate.
So I guess I somehow need to assign each of the six {{title}}
as a value to a ampscript variable like @title1 – @title6

How can I do that?

%%[
var @json
set @json = HttpGET("https://example.com")
]%%


{{.datasource JSONVar type=variable maxRows = 6}}
{{.data}}
{ "target" : "@json" }
{{/data}}


{{.datasource items type=nested maxRows = 6}}
{{.data}}
{ "target" : "JsonVar.items" }
{{/data}}

Title: {{title}}<br>

{{/datasource}}
{{/datasource}}

The upper part of the json looks like this:

[ { "id":"123", "title":"Titlename", "component":"default", "items":[ { "title":"TitleAgain", "assetId":456, "asset":{ "id":345, "categoryId":789, "images":{ "portrait":[ { "width":189

Best Answer

You can use ServerSide Javascript in emails. Place this code at the top of the page.

This code will loop through the JSON and create (and set) the variables to be available in Ampscript.

<script runat=server>
Platform.Load("Core","1");

var json = '[ { "id":"123", "title":"Titlename1" }, { "id":"456", "title":"Titlename2" }, { "id":"789", "title":"Titlename3" } ]';

// Parse JSON
var jsonObject = Platform.Function.ParseJSON(json);
var list = jsonObject;

// Loop through all items in the list (JSON)
for(var i = 0; i < list.length; i++ ) {
    var listItem = list[i];

    // Set List item info
    var id = listItem['id'];
    var title = listItem['title'];

    // Set variabele name
    var loopNr = (i+1); // Add 1 because loop starts at 0
    var variableName = ("@title"+loopNr); // Combine word title with number of loop

    // Write variabele to AMPscript for further processing
    Platform.Variable.SetValue(variableName, title);
}
</script>

<h1>Available in AMPscript:</h1>
Title 1: %%=v(@title1)=%% <br />
Title 2: %%=v(@title2)=%% <br />
Title 3: %%=v(@title3)=%% <br />

Hope this helps.

Related Topic