AI Agent Output Issue

Describe the problem/error/question

Would really appreciate some help. I get output from my Postges (or simple memory) that includes ““ and \n\n for line breaks. I’ve tried many combinations of code to remove the quotes and \n\n and have proper line breaks but nothing has worked. ChatGPT, Claude, Google, Reddit, n8n chat with notes using DeepThinking and still no working solution. Please help!

Using the most recent n8n version self-hosted using Docker.

What is the error message (if any)?

Please share your workflow



Share the output returned by the last node

Information on your n8n setup

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:

Try this

The "" and \n\n in your Postgres output are escaped strings. In n8n, you can clean them up using a Code node with JavaScript:

return items.map(item => {
let text = item.json.text || ‘’;
// Remove double quotes and convert \n\n to real line breaks
text = text.replace(/“”/g, ‘’).replace(/\n\n/g, ‘\n\n’);
return { json: { …item.json, text } };
});

Key points:

  • Use \\n in regex to match literal \n in strings from databases.

  • Always return a new item object; don’t modify the input in-place.

  • This works in the latest n8n Docker version.

If it’s not work then share as text your actual content.

The best way to introduce changes to the output of the AI Agent is to prompt for it.
In your system prompt explicitly explain the format you require the output to be in, for instance:

Output requirements:
- Do not wrap the result in quotation marks.
- Do not use quotation marks anywhere in the response.
- Do not include line breaks "\n", instead introduce actual line breaks.

Thank you for helping me verbalize the issue - after more trial and error this is the code that worked for me.

return items.map(item => {
let s = item.json.output ?? item.json.text ?? ‘’;
if (typeof s !== ‘string’) s = String(s);

// JSON-encoded string? Parse once.
if (/^“(?:\.|[^”])*"$/.test(s)) { try { s = JSON.parse(s); } catch {} }

// Normalize newlines
s = s.replace(/\r\n/g, ‘\n’)
.replace(/\n/g, ‘\n’)
.replace(/\r\n?/g, ‘\n’)
.trim();

s = s.replace(/\n{3,}/g, ‘\n\n’); // optional

return { json: { …item.json, text: s } };
});

1 Like

Thank you! I will also give that a go!

I’m glad to know my solution is working. Could you please mark this question as ‘Solutions’?

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