#Dataflow Automation - Converting MultiSelect List to JSON
Here is a solution to convert comma separated values (like from an iForm MultiSelect Field) into JSON.
In your transformation bucket, copy/paste the following JavaScript in the Transform Code text area
function MultiSelectToJSON(r,multi_list_keys) {
var keys = Object.keys(r);
for(var i = 0; i < keys.length; i++) {
if(multi_list_keys.hasOwnProperty(keys[i])) {
r[keys[i]] = ListToJSON(multi_list_keys[keys[i]],record[keys[i]]);
}
}
return(r);
}
function ListToJSON(key_name,list_of_items) {
var listAsArray = list_of_items.split(",");
var listAsJSON = [];
for(var i = 0; i < listAsArray.length; i++) {
tmp = {[key_name]: listAsArray[i]};
listAsJSON.push(tmp)
}
return listAsJSON;
}
Then, in the Transform Return text field type the following:
MultiSelectToJSON(record,{"ORIGINAL_KEY":"SUB_KEY"})
Make these two replacements to the above code:
- Replace ORIGINAL_KEY with the Data Column Name of the MultiSelect
- Replace SUB_KEY with the key name you want associated for each value
If my record has more than one MultiSelect field, separate ORIGINAL_KEY:SUB_KEY pairs from one another with a comma. For example:
MultiSelectToJSON(record,{"languages":"language","goals":"goal"})
This is before/after snapshots of the record:
Before
{
"first_name": "Jet",
"last_name": "Li",
"languages": "spanish,french,german,korean",
"goals": "concentration,physical_fitness,meeting_new_people,role_models"
}
After
[ { "first_name": "Jet", "last_name": "Li", "languages": [ { "language": "spanish" }, { "language": "french" }, { "language": "german" }, { "language": "korean" } ], "goals": [ { "goal": "concentration" }, { "goal": "physical_fitness" }, { "goal": "meeting_new_people" }, { "goal": "role_models" } ] } ]
Hope this helps!
Please sign in to leave a comment.
Comments
0 comments