Transform Single Item to Many and Add Labels

Describe the issue/error/question

I obtain flat text data from a fairly primitive API in the format:

[
{
"data":
"RT/5.0.3 200 Ok 226335: TEST ESCALATION 226354: ANOTHER TEST ESCALATION "
}
]

I am transforming this to a single item using this code:

return items[0].json.data.split('\n').reduce((tickets, currentValue) => {
  const stringParts = currentValue.split(':');
  if (stringParts.slice(0).length > 1) {
    tickets[stringParts.slice(0)[0]] = stringParts.slice(1).join(':');    
  }
  return tickets;
}, {});

The result is:

[
{
"226335":
" TEST ESCALATION",
"226354":
" ANOTHER TEST ESCALATION"
}
]

This, however, is not usable in n8n because it is a single item. My question is, how do I transform this to a format that is usable by n8n? I think I need to add labels and convert this single item to multiple items.

What is your desired data format?

I believe my desired output is:

[
{
"id": 226335,
"title":"TEST ESCALATION"
},
"id":226354,
"title":"ANOTHER TEST ESCALATION"
}
]

How can I get my data into this format?

Information on your n8n setup

  • n8n version: 0.214.2
  • Database you’re using (default: SQLite): SQLLite
  • Running n8n with the execution process [own(default), main]: own
  • Running n8n via [Docker, npm, n8n.cloud, desktop app]: Docker

Hi @cranious, welcome to the community. The format that you mention under desired format is correct. Unfortunately, you data structure is really hard to parse into this… when I ran your code snippe above, I also got a completely different result than you mentioned.

I created a code that would work, based on a few assumptions:

  • IDs are always 6 digit
  • There are no characters after the last id-title pair

Feel free to use it:

let data = items[0].json.data;
const pattern = /\d{6}:/g;
const matches = data.match(pattern);
// get id value pairs
let pairs = [];
matches.reverse().forEach(match => {
  let index = data.indexOf(match);
  let substring = data.slice(index);
  pairs.push(substring);
  data = data.replace(substring,"");
})
// split pairs
const result = pairs.map(pair => {
  keyValue = pair.split(":");
  return {
    "id": keyValue[0],
    "title": keyValue[1]
  }
})
console.log(result);
return result;

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.