/n8n-tutorials

How to handle escaped JSON from Cohere output in n8n?

Learn how to parse and handle escaped JSON from Cohere API output in n8n using JSON Parse and Function nodes for seamless workflow integration.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free consultation

How to handle escaped JSON from Cohere output in n8n?

To handle escaped JSON from Cohere output in n8n, you need to parse the escaped string into a usable JSON object. This typically involves using the JSON Parse node with appropriate configuration to process the escaped characters in the Cohere API response.

 

Step 1: Understand the Cohere Output Problem

 

When working with the Cohere API in n8n, you might receive responses where JSON is escaped within a string. This means the actual JSON structure is represented as a text string with escape characters (like " or \n), making it difficult to access the nested properties directly.

For example, instead of getting a proper JSON object like:


{
  "generations": [
    {
      "text": "Some response text",
      "data": { "key": "value" }
    }
  ]
}

You might receive an escaped string representation like:


{
  "response": "{"generations":[{"text":"Some response text","data":{"key":"value"}}]}"
}

 

Step 2: Create Your Workflow with Cohere Node

 

First, set up your workflow with a trigger node and the Cohere node:

  1. Add a trigger node (e.g., Manual Trigger) to start your workflow
  2. Add the Cohere node and configure it with your API key
  3. Set up the appropriate operation (Generate, Summarize, etc.)
  4. Configure any necessary parameters
  5. Save and execute the node to test the connection

 

Step 3: Examine the Cohere Response

 

After running the Cohere node, examine the output to identify the escaped JSON:

  1. Add a "Debug" node after the Cohere node
  2. Execute the workflow
  3. Check the output in the debug panel
  4. Look for nested JSON strings that contain escape characters (like ")

 

Step 4: Add a JSON Parse Node

 

To handle the escaped JSON, add a JSON Parse node:

  1. Add a "JSON Parse" node after the Cohere node
  2. Connect it to the Cohere node's output

[Cohere Node] → [JSON Parse Node]

 

Step 5: Configure the JSON Parse Node

 

Configure the JSON Parse node to handle the escaped JSON:

  1. In the JSON Parse node settings, select "Property" mode
  2. In the "Property" field, enter the path to the escaped JSON string
  • This is usually something like data.response or json.generations
  • The exact path depends on your Cohere node's output structure
  1. Enable "Keep Only Parsed Data" if you want only the parsed JSON in the output

{
  "parameters": {
    "mode": "property",
    "property": "json.response", // Adjust this path based on your Cohere output
    "options": {
      "keepOnlyParsed": true
    }
  }
}

 

Step 6: Handle Deeply Nested Escaped JSON

 

Sometimes, the escaped JSON might be deeply nested or appear in an array. In such cases:

  1. Use the Function node to extract and parse the JSON manually:

// Add this Function node after the Cohere node
const cohere\_response = items[0].json; // Adjust according to your data structure

// Find the escaped JSON string (path may vary)
const escapedJson = cohere\_response.response; // Or another path where your escaped JSON is

// Parse the escaped JSON into an actual object
const parsedData = JSON.parse(escapedJson);

// Return the parsed data
return [{
  json: parsedData
}];

 

Step 7: Access the Parsed JSON Data

 

After parsing, you can now access the properties directly:

  1. Add nodes that need to work with the parsed JSON data after the JSON Parse node
  2. In expression fields, reference the parsed data using standard expressions
  3. For example, to access the first generation's text:

{{ $node["JSON Parse"].json.generations[0].text }}

 

Step 8: Handle Arrays of Escaped JSON

 

If you receive an array of items with escaped JSON, use a "Split In Batches" node followed by a "JSON Parse" node in a loop:

  1. Add a "Split In Batches" node after the Cohere node
  2. Configure it to split the array into individual items
  3. Add a "JSON Parse" node after the Split node
  4. Configure it as in Step 5 for each item
  5. Use a "Merge" node to recombine the parsed results if needed

 

Step 9: Error Handling

 

Add error handling to manage parsing failures:

  1. Add an "IF" node after the JSON Parse node
  2. Set a condition to check if parsing was successful
  3. Create an "Error" branch for handling parsing failures
  4. In the Error branch, add a "Set" node to set a default value or error message

// Condition for IF node
{{ $node["JSON Parse"].json !== undefined }}

 

Step 10: Test and Verify

 

Finally, test your workflow to ensure the escaped JSON is correctly parsed:

  1. Add a final "Debug" node to view the processed data
  2. Execute the workflow
  3. Verify that the escaped JSON has been properly parsed
  4. Check that you can access all required properties directly
  5. Make any necessary adjustments to the JSON Parse configuration

 

Alternative Solution Using Function Node Only

 

If the JSON Parse node doesn't work for your specific case, use a dedicated Function node:


// Complete solution using Function node
function processCohere(items) {
  try {
    const cohereResponse = items[0].json;
    
    // Identify where the escaped JSON is in your response
    // This path will vary depending on your Cohere API call
    const escapedJsonPath = cohereResponse.response || 
                           cohereResponse.generations || 
                           cohereResponse.result;
    
    // If it's a string, parse it
    let parsedData;
    if (typeof escapedJsonPath === 'string') {
      parsedData = JSON.parse(escapedJsonPath);
    } else {
      // If it's already an object, use it directly
      parsedData = escapedJsonPath;
    }
    
    // Return the clean, parsed data
    return [{
      json: {
        original: cohereResponse,
        parsed: parsedData
      }
    }];
  } catch (error) {
    // Handle any parsing errors
    return [{
      json: {
        error: true,
        message: `Failed to parse Cohere response: ${error.message}`,
        original: items[0].json
      }
    }];
  }
}

return processCohere(items);

By following these steps, you'll be able to properly handle and work with escaped JSON from Cohere API responses in your n8n workflows, making the data accessible and usable for subsequent operations.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022