Parsing JSON with AMPscript and SSJS

Okay, the title is a bit misleading. Currently, it’s not entirely possible to parse JSON using only AMPscript, similar to how you can use the AMPscript function to BuildRowSetFromString. But, you can use Server Side Javascript (SSJS) in combination with AMPscript to set variables to use in AMPscript. Also you can use Guide Template Language (GTL) to parse JSON.

First we’ll go through an example of using SSJS in combination with AMPscript. AMPscript can be used for the JSON value and the SSJS will be used to actually parse the JSON. Then the AMPscript is set in the SSJS to be used anywhere else as that AMPscript variable.

SSJS and AMPscript:


The ParseJSON function:

Parses the supplied string or array value and returns an object from that value. This function will not execute functions within the supplied values.

Below is another example that sets the val variable to propVal.

<script runat="server">
     var str = '{ "prop1": "propVal" }';
     var obj = Platform.Function.ParseJSON(str);
     var val = obj.prop1;

From here you can use a For Loop to retrieve all the values in the JSON if the example had more data in it.

Also note that you should avoid using SSJS in your email and this should be run in your CloudPages/Microsite. To parse JSON in emails, you can use Guide Template Language (GTL) which I will cover below.

Guide Template Language (GTL):

Guide Template Language (GTL) is declarative syntax using Handlebars and Mustache template languages.

Handlebars.js is a simple templating language. It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions (curly brackets), i.e.

<p>Hello {{First Name}} {{Last Name}} from {{City}}.<p>

Mustache is a logic-less template syntax that can be used for HTML and works by expanding tags in a template using values provided in a hash or object. Mustache templates can be used anywhere you can use JavaScript.

Guide Template Language allows for parsing of JSON objects which we will cover below.


set @JSON = ‘[{“Site”: “”,”email”: “”},{“Site”: “”,”email”: “”}]’


%%{={{ }}=}%%

{{.dataobject JSONVar type=variable source=@JSON maxrows=5}}
{{#each JSONVar}}

Site: {{site}}
Email: {{email}} {{/each}}

Note that the added  %%{={{ }}=}%% at the top of the GTL code. This resets the GTL delimiters in CloudPages and Microsites/Landing Pages.






There you have it. Parsing JSON is possible using a combination of SSJS and AMPscript or using Guide Template Language. If you’re crafty with BuildRowSetFromString, you may be able to parse your JSON using entirely in AMPscript but it may not be a scalable solution.

Let me know in the comments below if you’ve tried something similar with parsing JSON in Salesforce Marketing Cloud.

Leave a Reply

Your email address will not be published. Required fields are marked *