Skip to main content
RapidDev - Software Development Agency
n8n-tutorial

How to Handle Escaped JSON from Cohere Output in n8n

Cohere models sometimes return JSON with double-escaped characters — backslashes before quotes (\\\"key\\\" instead of \"key\"), escaped newlines (\\n), and Unicode escape sequences. Fix this by unescaping the string in a Code node before parsing, using the Structured Output Parser for automatic handling, and adjusting your Cohere prompt to request clean JSON output.

What you'll learn

  • How to identify and unescape double-escaped JSON from Cohere
  • How to build a robust unescaping function in a Code node
  • How to use the Structured Output Parser with Cohere to avoid escaping issues
  • How to handle Cohere-specific response format quirks
Book a free consultation
4.9Clutch rating
600+Happy partners
17+Countries served
190+Team members
Advanced9 min read15-20 minutesn8n 1.20+ with Cohere Chat Model sub-nodeMarch 2026RapidDev Engineering Team
TL;DR

Cohere models sometimes return JSON with double-escaped characters — backslashes before quotes (\\\"key\\\" instead of \"key\"), escaped newlines (\\n), and Unicode escape sequences. Fix this by unescaping the string in a Code node before parsing, using the Structured Output Parser for automatic handling, and adjusting your Cohere prompt to request clean JSON output.

Why Cohere Returns Escaped JSON in n8n

When Cohere models return JSON in n8n workflows, the output often contains double-escaped characters. This happens because Cohere's API serializes the response text as a JSON string value, which escapes special characters. When n8n then includes this in its own JSON data structure, the escaping can be doubled. For example, a quote (") becomes \" in the first serialization, then \\" in the second. Similarly, newlines (\n) become \\n. When you try to JSON.parse() this double-escaped string, it either fails with a syntax error or produces an object with literal backslash characters in the values. This issue is specific to how Cohere's response format interacts with n8n's data handling.

Prerequisites

  • A running n8n instance with Cohere API credentials configured
  • A workflow using the Cohere Chat Model sub-node that requests JSON output
  • Basic understanding of JSON escaping rules and n8n Code nodes

Step-by-step guide

1

Inspect the Raw Cohere Output

Before fixing the issue, you need to see exactly what Cohere returns. Add a Code node after your LLM node and log the raw output. Look for patterns like: double backslashes before quotes (\\\"), escaped newlines as literal \\n characters, and Unicode escape sequences like \\u0022. Also check if the output is a string containing JSON (needs parsing) or already a parsed object (just needs unescaping of values). The inspection tells you which unescaping strategy to use.

typescript
1const raw = $json.text || $json.output || $json.message?.content || '';
2
3// Diagnostic output
4return [{
5 json: {
6 raw_type: typeof raw,
7 raw_length: raw.length,
8 first_chars: raw.substring(0, 300),
9 has_double_backslash: raw.includes('\\\\'),
10 has_escaped_quotes: raw.includes('\\"'),
11 has_literal_backslash_n: raw.includes('\\n'),
12 starts_with_quote: raw.startsWith('"'),
13 raw_output: raw
14 }
15}];

Expected result: You can see the exact escaping patterns in Cohere's output.

2

Unescape the Cohere Output in a Code Node

Add a Code node that systematically unescapes the Cohere output before parsing it as JSON. The function handles multiple layers of escaping that can occur depending on how the response passes through n8n's data pipeline. Set the Code node to 'Run Once for Each Item'. This function tries progressive unescaping until it finds valid JSON.

typescript
1const raw = $json.text || $json.output || $json.message?.content || '';
2
3function unescapeAndParse(text) {
4 let str = text.trim();
5
6 // If the entire output is wrapped in outer quotes, remove them
7 if (str.startsWith('"') && str.endsWith('"')) {
8 try {
9 str = JSON.parse(str); // This unescapes one level
10 } catch (e) {
11 str = str.slice(1, -1);
12 }
13 }
14
15 // Attempt 1: Direct parse
16 try {
17 return JSON.parse(str);
18 } catch (e) {}
19
20 // Attempt 2: Unescape double-escaped characters
21 let unescaped = str
22 .replace(/\\\\/g, '\\') // \\\\ → \\
23 .replace(/\\"/g, '"') // \\" → "
24 .replace(/\\n/g, '\n') // \\n → newline
25 .replace(/\\t/g, '\t') // \\t → tab
26 .replace(/\\r/g, '\r'); // \\r → return
27
28 try {
29 return JSON.parse(unescaped);
30 } catch (e) {}
31
32 // Attempt 3: Strip markdown fences then retry
33 const fenceMatch = str.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
34 if (fenceMatch) {
35 try {
36 return JSON.parse(fenceMatch[1].trim());
37 } catch (e) {}
38 }
39
40 // Attempt 4: Extract JSON object from surrounding text
41 const jsonMatch = str.match(/\{[\s\S]*\}/);
42 if (jsonMatch) {
43 try {
44 return JSON.parse(jsonMatch[0]);
45 } catch (e) {}
46 }
47
48 return null;
49}
50
51const parsed = unescapeAndParse(raw);
52
53if (parsed) {
54 return [{ json: { data: parsed, parse_status: 'success' } }];
55}
56
57return [{ json: { raw_text: raw, parse_status: 'failed' } }];

Expected result: Double-escaped JSON from Cohere is correctly unescaped and parsed into a JavaScript object.

3

Use the Structured Output Parser with Cohere

The Structured Output Parser handles some escaping issues automatically because it instructs the model to return JSON in a specific format and then processes the output. Connect the Cohere Chat Model sub-node to an AI Agent or Basic LLM Chain, then add the Structured Output Parser. Define your schema. The parser adds formatting instructions to the prompt and handles initial parsing. For additional safety, also add the Auto-Fixing Output Parser.

Expected result: The Structured Output Parser handles Cohere's output formatting, reducing the need for manual unescaping.

4

Optimize Your Cohere Prompt for Clean JSON

Cohere's Command models respond well to explicit formatting instructions. Add specific directives to your system prompt that minimize escaping issues. Cohere's preamble parameter (available in the Cohere Chat Model sub-node) is particularly effective for this purpose — it acts as a system-level instruction that the model respects more consistently.

typescript
1// Cohere preamble (system prompt) for clean JSON output:
2const preamble = `You are a data extraction API.
3
4RULES:
51. Return ONLY a single JSON object
62. Do not escape characters unnecessarily
73. Use standard double quotes for JSON keys and string values
84. Do not wrap the JSON in markdown code fences
95. Do not add explanatory text before or after
106. Do not double-escape special characters
117. Newlines in string values should be \\n (single escape)
12
13The response MUST start with { and end with }
14
15Output schema:
16{"field1": "string", "field2": number, "items": ["array of strings"]}`;

Expected result: Cohere returns cleaner JSON with fewer escaping issues.

5

Handle Cohere-Specific Response Wrapper Fields

Cohere's API response includes additional metadata fields that other LLM APIs do not have, such as generation_id, citations, and search_results. When using the HTTP Request node to call Cohere directly, the JSON response you need is nested inside the response object. Extract the text field correctly before attempting to parse it as your structured data.

typescript
1// When using HTTP Request node to call Cohere Chat API directly:
2// The response structure is:
3// {
4// "response_id": "...",
5// "text": "<your JSON output here>",
6// "generation_id": "...",
7// "chat_history": [...],
8// "finish_reason": "COMPLETE",
9// "meta": { "api_version": {...}, "billed_units": {...} }
10// }
11
12// Extract the text field which contains your actual LLM output
13const cohereResponse = $json;
14const llmOutput = cohereResponse.text || '';
15
16// Now unescape and parse as shown in previous steps
17let cleaned = llmOutput.trim();
18if (cleaned.startsWith('"') && cleaned.endsWith('"')) {
19 try { cleaned = JSON.parse(cleaned); } catch(e) { cleaned = cleaned.slice(1,-1); }
20}
21
22try {
23 const data = JSON.parse(cleaned);
24 return [{ json: { data, cohere_meta: cohereResponse.meta } }];
25} catch (e) {
26 return [{ json: { raw: llmOutput, parse_error: e.message } }];
27}

Expected result: Cohere's response wrapper is handled correctly and the nested JSON output is extracted and parsed.

Complete working example

cohere-json-unescaper.js
1// Code node: Run Once for Each Item
2// Complete Cohere JSON unescaping and parsing pipeline
3
4const raw = $json.text || $json.output || $json.message?.content || '';
5
6function unescapeCohere(text) {
7 if (!text || typeof text !== 'string') return null;
8 let str = text.trim();
9
10 // Step 1: Remove outer string quotes if present
11 if ((str.startsWith('"') && str.endsWith('"')) ||
12 (str.startsWith("'") && str.endsWith("'"))) {
13 try {
14 str = JSON.parse(str);
15 if (typeof str !== 'string') return str; // Already parsed to object
16 } catch (e) {
17 str = str.slice(1, -1);
18 }
19 }
20
21 // Step 2: Remove markdown fences
22 const fenceMatch = str.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);
23 if (fenceMatch) str = fenceMatch[1].trim();
24
25 // Step 3: Try direct parse
26 try { return JSON.parse(str); } catch (e) {}
27
28 // Step 4: Fix double escaping
29 const fixes = [
30 [/\\\\"/g, '"'], // \\" → "
31 [/\\\\/g, '\\'], // \\\\ → \\
32 [/\\n/g, '\n'], // Escaped newlines
33 [/\\t/g, '\t'], // Escaped tabs
34 [/\\r/g, '\r'], // Escaped returns
35 [/\\u0022/g, '"'], // Unicode quote escapes
36 [/\\u0027/g, "'"], // Unicode apostrophe
37 [/\\\//g, '/'] // Escaped forward slashes
38 ];
39
40 let fixed = str;
41 for (const [pattern, replacement] of fixes) {
42 fixed = fixed.replace(pattern, replacement);
43 }
44
45 try { return JSON.parse(fixed); } catch (e) {}
46
47 // Step 5: Extract JSON object from surrounding text
48 const objectMatch = fixed.match(/\{[\s\S]*\}/);
49 if (objectMatch) {
50 try { return JSON.parse(objectMatch[0]); } catch (e) {}
51 }
52
53 // Step 6: Try one more level of unescaping
54 try {
55 const doubleUnescaped = JSON.parse('"' + fixed + '"');
56 if (typeof doubleUnescaped === 'string') {
57 return JSON.parse(doubleUnescaped);
58 }
59 } catch (e) {}
60
61 return null;
62}
63
64const result = unescapeCohere(raw);
65
66if (result !== null) {
67 return [{
68 json: {
69 data: result,
70 parse_status: 'success',
71 source: 'cohere'
72 }
73 }];
74}
75
76return [{
77 json: {
78 raw_text: raw,
79 parse_status: 'failed',
80 source: 'cohere',
81 suggestion: 'Check if the Cohere output format has changed or if the prompt needs adjustment'
82 }
83}];

Common mistakes when handling Escaped JSON from Cohere Output in n8n

Why it's a problem: Applying OpenAI/Claude JSON parsing logic to Cohere output without adapting for double escaping

How to avoid: Cohere's escaping patterns differ. Specifically handle double-escaped quotes (\\\") and escaped forward slashes (\/) which are uncommon in other LLM outputs.

Why it's a problem: Using string.replace() without the global flag, only fixing the first occurrence

How to avoid: Always use regex with the /g flag for replacements: str.replace(/\\\"/g, '"') instead of str.replace('\\"', '"').

Why it's a problem: Not handling the case where Cohere wraps the entire JSON string in outer quotes

How to avoid: Check if the output starts and ends with quotes. If so, use JSON.parse() on the whole string first to remove one escaping layer, then parse the inner string.

Why it's a problem: Assuming Cohere's response structure matches OpenAI's

How to avoid: Cohere's API response uses a 'text' field (not 'choices'). When using the HTTP Request node, extract $json.text, not $json.choices[0].message.content.

Best practices

  • Always add an unescaping Code node after Cohere LLM nodes — Cohere's escaping behavior differs from OpenAI and Claude
  • Use the Structured Output Parser with Cohere to reduce but not eliminate escaping issues
  • Include explicit 'do not double-escape' instructions in Cohere's preamble parameter
  • Test your JSON parsing with various Cohere models (Command, Command-R) as they may escape differently
  • Log raw Cohere output before unescaping during development to understand the exact patterns
  • Use temperature 0 with Cohere when requesting JSON to minimize format variation
  • Handle Unicode escape sequences (\u0022) alongside standard escaping patterns
  • Set the Cohere response_format parameter to JSON when available in the API

Still stuck?

Copy one of these prompts to get a personalized, step-by-step explanation.

ChatGPT Prompt

I'm using Cohere in n8n and the JSON output has double-escaped characters — backslashes before quotes and escaped newlines. How do I unescape the Cohere output in a Code node and parse it as valid JSON?

n8n Prompt

Fix escaped JSON from Cohere in my n8n workflow. The Cohere Chat Model returns JSON with double-escaped quotes (\\" instead of ") and escaped newlines (\\n). Add a Code node that unescapes these patterns and parses the result into a JavaScript object.

Frequently asked questions

Why does Cohere double-escape JSON but OpenAI does not?

Cohere's API may serialize the model's text output as a JSON string value, which adds one layer of escaping. When n8n then includes this in its data pipeline as another JSON value, the escaping doubles. OpenAI's newer API versions handle this differently in their response serialization.

Does this issue affect all Cohere models?

The escaping behavior can vary between Cohere model versions (Command, Command-R, Command-R+). Always test your unescaping code with the specific model you are using, and add logging to detect if the behavior changes after model updates.

Can I avoid the escaping issue by using the HTTP Request node instead of the Cohere Chat Model sub-node?

Using the HTTP Request node gives you more control over response handling, but the underlying escaping comes from Cohere's API response format, not from n8n's node. You will still need to unescape, but you can process the response more precisely.

What if the unescaped output is still not valid JSON?

If unescaping does not produce valid JSON, the model likely generated malformed JSON. Use the Auto-Fixing Output Parser to send the broken output back to Cohere with instructions to fix it, or restructure your prompt to request simpler output.

Is there a Cohere API setting to prevent double escaping?

Cohere's API does not have a setting to control output escaping. The escaping occurs at the API response serialization level. Your best mitigation is prompt engineering (requesting raw JSON) combined with Code node unescaping.

Can RapidDev help integrate Cohere with n8n for production use?

Yes. RapidDev can build n8n workflows with Cohere integration that handle all output formatting quirks, including escaped JSON, incomplete responses, and multi-turn conversation management.

RapidDev

Talk to an Expert

Our team has built 600+ apps. Get personalized help with your project.

Book a free consultation

Need help with your project?

Our experts have built 600+ apps and can accelerate your development. Book a free consultation — no strings attached.

Book a free consultation

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We'll discuss your project and provide a custom quote at no cost.