Skip to main content

JSON Parsing Errors

Problem: Unable to parse agent responses as JSON Solution: Request specific JSON format and implement robust parsing

Request Clean JSON

Always specify that you want raw JSON without markdown:
await client.sendMessage(sessionId, `
    Extract product information.

    Return ONLY valid JSON (no markdown, no explanations):

    {
        "products": [
            {
                "name": "Product Name",
                "price": 99.99
            }
        ]
    }

    Do not wrap in markdown code blocks.
    Do not include any text before or after the JSON.
`);

Robust JSON Parsing

Handle cases where agent wraps JSON in markdown:
function parseAgentJson(response) {
  try {
    // Try direct parse
    return JSON.parse(response);
  } catch (e) {
    // Try extracting JSON from markdown
    const jsonMatch = response.match(/```json\n([\s\S]*?)\n```/);
    if (jsonMatch) {
      return JSON.parse(jsonMatch[1]);
    }

    // Try finding JSON object
    const jsonObjectMatch = response.match(/\{[\s\S]*\}/);
    if (jsonObjectMatch) {
      return JSON.parse(jsonObjectMatch[0]);
    }

    throw new Error('No valid JSON found in response');
  }
}

// Usage
const result = await session.runTask('Extract product info as JSON');
const data = parseAgentJson(result);
Always specify the exact JSON structure you expect in your instructions. This helps the agent return properly formatted data.