Google Pie Chart报错:首行非数组,ASP.NET页面API数据加载求助
Hey there! Let's break down why you're hitting that error and how to fix it quickly.
The Root Cause
Google Pie Chart's arrayToDataTable() method expects a 2-dimensional array as input. The structure needs to look like this:
[ ["Category", "Count"], // Header row ["Status 2", 5], // Data row 1 ["Status 3", 1] // Data row 2 ]
But your API is returning an array of JSON objects, which Google Charts can't interpret directly—hence the "First row is not an array" error.
Solution 1: Convert Data on the Frontend (JavaScript)
If you can't modify the API response, transform the object array into the required 2D array in your frontend code. Here's how to do it:
// Assume this is the raw data you fetched from your API const rawApiData = [{"AuditStatusId":2,"Number":5},{"AuditStatusId":3,"Number":1}, {"AuditStatusId":19,"Number":1},{"AuditStatusId":23,"Number":27}, {"AuditStatusId":24,"Number":2},{"AuditStatusId":27,"Number":1}, {"AuditStatusId":31,"Number":1},{"AuditStatusId":38,"Number":1}]; // Transform into Google Charts-compatible format const chartReadyData = [['Audit Status', 'Entry Count']]; // Add header row rawApiData.forEach(status => { // Replace `Status ${status.AuditStatusId}` with actual status names if you have them! chartReadyData.push([`Status ${status.AuditStatusId}`, status.Number]); }); // Initialize and draw the chart google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawPieChart); function drawPieChart() { const data = google.visualization.arrayToDataTable(chartReadyData); const options = { title: 'Audit Status Distribution', pieHole: 0.3 // Optional: Add a donut style if you want }; const chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); }
Solution 2: Modify the ASP.NET API to Return the Correct Format
If you control the API, you can adjust it to send the 2D array directly, saving frontend work. Here's an example in C#:
// Inside your API controller action public IActionResult GetAuditStatusData() { // Assume this is your existing data retrieval logic var auditStatuses = _dbContext.AuditStatusSummaries.ToList(); // Build the 2D array structure var chartData = new List<object>(); // Add header row chartData.Add(new List<object> { "Audit Status", "Entry Count" }); // Add data rows foreach (var status in auditStatuses) { // Again, replace with actual status names if available chartData.Add(new List<object> { $"Status {status.AuditStatusId}", status.Number }); } return Ok(chartData); }
Pro Tip
If you have a lookup table for AuditStatusId (e.g., 2 = "Approved", 3 = "Pending"), replace the $"Status {status.AuditStatusId}" string with the human-readable name. This will make your pie chart labels way more useful!
内容的提问来源于stack exchange,提问作者Khaksar

