Create 3 Multiple JSON Objects from a single JSON API Return that has "key1": "value1;value2;value3" style encoding

819 views Asked by At

I have been looking around a lot, and can't find a simple answer to my problem, I have seen how to do searching and things with LINQ to JSON (that seems to complex for my needs).

I am using n8n.io to try to execute a "WebHook Post" -> Function call -> Split to Batch (1) -> API Call

I have a JSON Object like this

$json = {
  "_id": "627bd2378b8bbe5c27a23669",
  "firstName": "John;Maria;Bruce",
  "lastName": "Doe;Phenix;Mclean",
}

I need to send each of these as 3 individual JSON objects to another webhook

I am trying to figure out a for loop that could take $json and turn it into $json[0], $json[1], $json[2]

Where

$json[0] = {
  "firstName": "John",
  "lastName": "Doe",
}

$json[1] = {
  "firstName": "Maria",
  "lastName": "Phenix",
}

$json[2] = 
  "firstName": "Bruce",
  "lastName": "Mclean",
}

I am having the hardest time finding the simplest and quickest way to go from A -> B any advice n8n.io allows me to take the $json.body from a previous step and process it with a javascript function?

Hoping there is some built-in method that can handle this translation in a step or two inside a for loop in Javascript.

//iterate through the combined JSON Object
for (var k of $json) {
  //grab the row and split the string into 3 
  String.split($json[k]);
  //Create a $newObj with a full set of data in each index
}
return $newObj
2

There are 2 answers

0
Roland Bough On BEST ANSWER

Big thanks to @metdodrbic for pointing me in the right direction.

His code worked 100%

I did have to edit the $json to $json.body because of the peculiar way n8n.io returns the JSON object from a previous step into the "function" block

const firstNames = $json.body.firstName.split(';');
const lastNames = $json.body.lastName.split(';');
const result = [];

for (let i = 0; i < firstNames.length; i++) {
  result.push({firstName: firstNames[i], lastName: lastNames[i]})  
}

1
metodribic On

I'm not familiar with n8n but if you can use javascript to process $json, then you can split the keys of specific properties and then concat them back with for loop like so:

const firstNames = $json.firstName.split(';');
const lastNames = $json.lastName.split(';');
const result = [];

for (let i = 0; i < firstNames.length; i++) {
  result.push({firstName: firstNames[i], lastName: lastNames[i]})  
}

Above code assumes that both firstName and lastName inside $json has the same amount of semicolon separated values. If one of the two can have more values than another, then I would suggest using Math.max to find the one with most values and use that one in for loop condition