Need help in some joson error

Hi, can anyone help to rectify this error “Parsed JSON does not have the expected ‘table’ structure with ‘cols’ and ‘rows’. [line 39]” to run “Build Your First AI Data Analyst Chatbot 2” the code is

// Ensure there's at least one input item.
if (!items || items.length === 0) {
  throw new Error("No input items found.");
}

// Our input is expected to have a 'data' property containing the JSONP string.
const input = items[0].json;

if (!input.data) {
  throw new Error("Input JSON does not have a 'data' property.");
}

const rawData = input.data.trim();

// Try to extract just the JSON part from the JSONP response
const start = rawData.indexOf('{');
const end = rawData.lastIndexOf('}');

if (start === -1 || end === -1 || end <= start) {
  throw new Error("Could not extract valid JSON from input.");
}

const jsonString = rawData.substring(start, end + 1);

// Parse the extracted JSON string.
let parsed;
try {
  parsed = JSON.parse(jsonString);
} catch (error) {
  console.error("⚠️ Failed to parse JSON string:", jsonString);
  throw new Error("Failed to parse JSON: " + error.message);
}

// Debug log to understand the structure
console.log("✅ Parsed JSON structure:", JSON.stringify(parsed, null, 2));

// Check if the expected structure exists
if (!parsed.table || !Array.isArray(parsed.table.cols) || !Array.isArray(parsed.table.rows)) {
  throw new Error("Parsed JSON does not have the expected 'table' structure with 'cols' and 'rows'.");
}

const cols = parsed.table.cols;
const rows = parsed.table.rows;

// Convert "Date(YYYY,M,D)" to "YYYY-MM-DD"
function formatDate(dateStr) {
  const match = dateStr.match(/^Date\((\d+),(\d+),(\d+)\)$/);
  if (!match) return dateStr;
  const year = parseInt(match[1], 10);
  const month = parseInt(match[2], 10) + 1;
  const day = parseInt(match[3], 10);
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}

// Map each row into an object using column labels
const newItems = rows.map(row => {
  const obj = {};
  cols.forEach((col, index) => {
    let value = row.c && row.c[index] ? row.c[index].v : null;
    if (col.type === "date" && typeof value === "string") {
      value = formatDate(value);
    }
    obj[col.label] = value;
  });
  return { json: obj };
});

// Return the array of transformed rows
return newItems;
1 Like

Hi @Ussama_Yaseen ,

Can you put that workflow code into a code block? It doesnt render into a workflow right now. Copy your n8n workflow, and paste it into a code block. Then we can copy your flow and help you with it.

Best,

Robert

Here’s a workflow to start with. You may need to convert the input to json like this.