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
Inspect the Raw Cohere Output
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.
1const raw = $json.text || $json.output || $json.message?.content || '';23// Diagnostic output4return [{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: raw14 }15}];Expected result: You can see the exact escaping patterns in Cohere's output.
Unescape the Cohere Output in a Code Node
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.
1const raw = $json.text || $json.output || $json.message?.content || '';23function unescapeAndParse(text) {4 let str = text.trim();56 // If the entire output is wrapped in outer quotes, remove them7 if (str.startsWith('"') && str.endsWith('"')) {8 try {9 str = JSON.parse(str); // This unescapes one level10 } catch (e) {11 str = str.slice(1, -1);12 }13 }1415 // Attempt 1: Direct parse16 try {17 return JSON.parse(str);18 } catch (e) {}1920 // Attempt 2: Unescape double-escaped characters21 let unescaped = str22 .replace(/\\\\/g, '\\') // \\\\ → \\23 .replace(/\\"/g, '"') // \\" → "24 .replace(/\\n/g, '\n') // \\n → newline25 .replace(/\\t/g, '\t') // \\t → tab26 .replace(/\\r/g, '\r'); // \\r → return2728 try {29 return JSON.parse(unescaped);30 } catch (e) {}3132 // Attempt 3: Strip markdown fences then retry33 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 }3940 // Attempt 4: Extract JSON object from surrounding text41 const jsonMatch = str.match(/\{[\s\S]*\}/);42 if (jsonMatch) {43 try {44 return JSON.parse(jsonMatch[0]);45 } catch (e) {}46 }4748 return null;49}5051const parsed = unescapeAndParse(raw);5253if (parsed) {54 return [{ json: { data: parsed, parse_status: 'success' } }];55}5657return [{ json: { raw_text: raw, parse_status: 'failed' } }];Expected result: Double-escaped JSON from Cohere is correctly unescaped and parsed into a JavaScript object.
Use the Structured Output Parser with Cohere
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.
Optimize Your Cohere Prompt for Clean JSON
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.
1// Cohere preamble (system prompt) for clean JSON output:2const preamble = `You are a data extraction API.34RULES:51. Return ONLY a single JSON object62. Do not escape characters unnecessarily73. Use standard double quotes for JSON keys and string values84. Do not wrap the JSON in markdown code fences95. Do not add explanatory text before or after106. Do not double-escape special characters117. Newlines in string values should be \\n (single escape)1213The response MUST start with { and end with }1415Output schema:16{"field1": "string", "field2": number, "items": ["array of strings"]}`;Expected result: Cohere returns cleaner JSON with fewer escaping issues.
Handle Cohere-Specific Response Wrapper Fields
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.
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// }1112// Extract the text field which contains your actual LLM output13const cohereResponse = $json;14const llmOutput = cohereResponse.text || '';1516// Now unescape and parse as shown in previous steps17let cleaned = llmOutput.trim();18if (cleaned.startsWith('"') && cleaned.endsWith('"')) {19 try { cleaned = JSON.parse(cleaned); } catch(e) { cleaned = cleaned.slice(1,-1); }20}2122try {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
1// Code node: Run Once for Each Item2// Complete Cohere JSON unescaping and parsing pipeline34const raw = $json.text || $json.output || $json.message?.content || '';56function unescapeCohere(text) {7 if (!text || typeof text !== 'string') return null;8 let str = text.trim();910 // Step 1: Remove outer string quotes if present11 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 object16 } catch (e) {17 str = str.slice(1, -1);18 }19 }2021 // Step 2: Remove markdown fences22 const fenceMatch = str.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);23 if (fenceMatch) str = fenceMatch[1].trim();2425 // Step 3: Try direct parse26 try { return JSON.parse(str); } catch (e) {}2728 // Step 4: Fix double escaping29 const fixes = [30 [/\\\\"/g, '"'], // \\" → "31 [/\\\\/g, '\\'], // \\\\ → \\32 [/\\n/g, '\n'], // Escaped newlines33 [/\\t/g, '\t'], // Escaped tabs34 [/\\r/g, '\r'], // Escaped returns35 [/\\u0022/g, '"'], // Unicode quote escapes36 [/\\u0027/g, "'"], // Unicode apostrophe37 [/\\\//g, '/'] // Escaped forward slashes38 ];3940 let fixed = str;41 for (const [pattern, replacement] of fixes) {42 fixed = fixed.replace(pattern, replacement);43 }4445 try { return JSON.parse(fixed); } catch (e) {}4647 // Step 5: Extract JSON object from surrounding text48 const objectMatch = fixed.match(/\{[\s\S]*\}/);49 if (objectMatch) {50 try { return JSON.parse(objectMatch[0]); } catch (e) {}51 }5253 // Step 6: Try one more level of unescaping54 try {55 const doubleUnescaped = JSON.parse('"' + fixed + '"');56 if (typeof doubleUnescaped === 'string') {57 return JSON.parse(doubleUnescaped);58 }59 } catch (e) {}6061 return null;62}6364const result = unescapeCohere(raw);6566if (result !== null) {67 return [{68 json: {69 data: result,70 parse_status: 'success',71 source: 'cohere'72 }73 }];74}7576return [{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.
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?
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.
Talk to an Expert
Our team has built 600+ apps. Get personalized help with your project.
Book a free consultation