Hi Team,
I need to use Velocity Script to show multiple product information from the Abandoned Cart Custom field in an email. The JSON object below has been stored in a Marketo custom field. Usually, we store cart values in a custom object, but in this case, they need to be stored in a custom field. I'm having difficulty converting the JSON data into a foreach loop.
@SanfordWhiteman @Darshil_Shah1 Could you please take a look at this and provide your insights?
{
"abandoned_cart": {
"11": {
"product_name_1": "ABCS",
"product_image_1": "3282.jpg",
"catalog_1": "960-13",
"quantity_1": "3",
"unit_1": "EA",
"tabl_value_2": "18 Mars 2019"
},
"13": {
"product_name_1": "BCSDA",
"product_image_1": "33282.jpg",
"catalog_1": "9610-1",
"quantity_1": "3",
"unit_1": "IN",
"tabl_value_2": "04 avril 2019"
},
"15": {
"product_name_1": "RTYU",
"product_image_1": "282.jpg",
"catalog_1": "6410-3",
"quantity_1": "3",
"unit_1": "US",
"tabl_value_2": "15-Avril-2019"
}
}
}
My velocity script:
#if( $lead.abandonedcart.isEmpty() )
#set( $lead.abandonedcart = '[]' )
#else
#set( $CartDetails = '#set( $CartDetails = ' + $lead.abandonedcart + ' )' )
#evaluate( $CartDetails )
## print $CartDetails
#end
Thanks,
Karthik
Solved! Go to Solution.
Iterating over a Map’s entries (entries = keys and values):
#foreach( $entry in $CartDetails.abandoned_cart.entrySet() )
#set( $key = $entry.getKey() )
#set( $value = $entry.getValue() )
## key is your object's numeric id
key: $key
product_name_1: $value.product_name_1
product_image_1: $value.product_image_1
#end
You haven’t provided enough detail.
If that JSON is stored in a lead field, and that field is named $lead.abandonedcart in Velocity, then your code is correct for parsing the JSON into a live Java Map object with a single top-level property abandoned_cart.
However, you’re talking about a #foreach and I don’t know what you’re expecting to iterate. Keys? Values? Entries?
Yes, as you mentioned, the JSON is stored in the Lead Abandoned Cart field. I am anticipating the headers and values to be presented like below. I believe that a Foreach loop would be return all values from JSON.
Please let me know if you need more information.
Expected output:
product_name_1 | product_image_1 | catalog_1 | quantity_1 | unit_1 |
ABCS | 3282.jpg | 960-13 | 3 | EA |
BCSDA | 33282.jpg | 9610-1 | 3 | IN |
RTYU | 282.jpg | 6410-3 | 3 | US |
Iterating over a Map’s entries (entries = keys and values):
#foreach( $entry in $CartDetails.abandoned_cart.entrySet() )
#set( $key = $entry.getKey() )
#set( $value = $entry.getValue() )
## key is your object's numeric id
key: $key
product_name_1: $value.product_name_1
product_image_1: $value.product_image_1
#end
Thanks @SanfordWhiteman. The code you provided is working, many thanks for your help.