How to Format a Multiline String from an AI Response
October 5, 2025
If you’re handling multiline text from an AI response, you’ll need to escape line breaks before sending it as JSON.
Introduction
When working with n8n and AI integrations, you might encounter a situation where the AI output is a multiline string that you want to use in a REST API request body. However, sending it directly often results in an invalid JSON body error.
In this post, I'll show you a simple way to fix this issue by escaping line breaks.
Simple fix
The reason it becomes an invalid JSON is that the text contains actual line breaks (\n
).
To make it valid, you need to escape those new line characters before sending the request.
{"content": "{{ $json.multiLineString.replace(/\n/g, "\\n") }} }}"}
Loading Tweet Button...