I have a JSON string which contains a 'body' key as a string, which is an escaped JSON that has keys and arrays. I want to read the JSON and extract the 'body' key and then extract the arrays inside the 'body' key and display the data from 'addresses' inside the email. How can I do this using AMPScript? If not possible in an elegant way in AMPScript, can I do it in SSJS?
{
"To": {
"Address": "[email protected]",
"SubscriberKey": "[email protected]",
"ContactAttributes": {
"SubscriberAttributes": {
"Body": "{\"country\":\"gb\",\"language\":\"en\",\"addresses\":[{\"type\":\"billing\",\"addrees\":\"BillingFirststreet\",\"City\":\"Amsterdam\",\"Country\":\"Netherlands\"},{\"type\":\"shipping\",\"addrees\":\"ShippingFirstlinestreet\",\"City\":\"DenHaag\",\"Country\":\"Netherlands\"}],\"type\":\"Order\",\"items\":[{\"productDisplayName\":\"TEST PRODUCT 1\",\"quantity\":1,\"code\":\"AB-45-EF\",\"price\":29.34,\"currencyCode\":\"EUR\"},{\"productDisplayName\":\"TEST PRODUCT 2\",\"quantity\":1,\"code\":\"AB-48-AF\",\"price\":192.4,\"currencyCode\":\"EUR\"}]}"
}
}
}
}
Unescaped Body string looks like below.
{
"country": "gb",
"language": "en",
"addresses": [
{
"type": "billing",
"addrees": "BillingFirststreet",
"City": "Amsterdam",
"Country": "Netherlands"
},
{
"type": "shipping",
"addrees": "ShippingFirstlinestreet",
"City": "DenHaag",
"Country": "Netherlands"
}
],
"type": "Order",
"items": [
{
"productDisplayName": "TEST PRODUCT 1",
"quantity": 1,
"code": "AB-45-EF",
"price": 29.34,
"currencyCode": "EUR"
},
{
"productDisplayName": "TEST PRODUCT 2",
"quantity": 1,
"code": "AB-48-AF",
"price": 192.4,
"currencyCode": "EUR"
}
]
}
I have the below code, Is there a better way to do this?
{{.datasource JSONVar source=@Json type=variable}}
{{.data}}
{ "target" : "@Json" }
{{/data}}
{{.datasource to_var type=nested}}
{{.data}}
{ "target" : "JSONVar.To" }
{{/data}}
{{.datasource cont_attr type=nested}}
{{.data}}
{ "target" : "to_var.ContactAttributes" }
{{/data}}
{{.datasource sub_attr type=nested}}
{{.data}}
{ "target" : "cont_attr.SubscriberAttributes" }
{{/data}}
%%[
set @payload =TreatAsContent('{{Body}}')
set @payload = ReplaceList(@payload, '', '\')
]%%
{{/datasource}}
{{/datasource}}
{{/datasource}}
{{/datasource}}
<b>Process Payload</b><br>
{{.datasource body_var type=variable}}
{{.data}}
{ "target" : "@payload" }
{{/data}}
country: {{country}}<br>
language: {{language}}<br>
{{.datasource items_var type=nested}}
{{.data}}
{ "target" : "body_var.addresses" }
{{/data}}
<br><b>Addresses</b><br>
<br>type: {{type}}
<br>addrees: {{addrees}}
<br>City: {{City}}
<br>Country: {{Country}} <br>
{{/datasource}}
{{/datasource}}