How to split json strings

Hi all.

Let’s say I have a text from one of the nodes like this:

[
    {
        "index": 0,
        "message": {
            "role": "assistant",
            "content": "**My Wonderful Family\nI live in a house near the mountains. I have two brothers and one sister, and I was born last. My father teaches mathematics, and my mother is a nurse at a big hospital. My brothers are very smart and work hard in school. My sister is a nervous girl, but she is very kind. My grandmother also lives with us. She came from Italy when I was two years old. She has grown old, but she is still very strong. She cooks the best food!",
            "logprobs": null,
            "finish_reason": "stop"
        }
    }
]

The question is how can I separate the title from the text?

I understand that I can split the text with
{{ $json.message.content.split(" “)[0] }},
{{ $json.message.content.split(” “)[1] }},
{{ $json.message.content.split(” ")[2] }}, etc., but the challenge is to separate not specific words, but specifically the first line in the json. I need an item that I can work with further with the following text: My Wonderful Family.

Is there any way to do this? I would be very grateful for help.

It looks like your topic is missing some important information. Could you provide the following if applicable.

  • n8n version:
  • Database (default: SQLite):
  • n8n EXECUTIONS_PROCESS setting (default: own, main):
  • Running n8n via (Docker, npm, n8n cloud, desktop app):
  • Operating system:
  • n8n version: 1.39.1
  • Database: Supabase
  • n8n EXECUTIONS_PROCESS setting: default
  • Running n8n via: Docker
  • Operating system: Windows 10, 22H2, 19045.4355

Hi @Hurricanenik ,

Your could use newline characters to mark where you want the text to be split and then select for the first line.

Something like:

const input = $json.message.content;

const textLines = input.split('\n');
const title = textLines[0];
const textBody = textLines.slice(1).join('\n')

const output = {
title: title;
text: textBody
};

return [{ json: output }];

Is this what you had in mind? :slight_smile:

1 Like

Thank you so much! The only thing I’d nitpick is that you don’t need the ; sign after the title: title.

Hopefully this will make it easier for those who have the same issue.

1 Like

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