Metricsgraphics.js折线图日期显示异常:数据库JSON数据适配问题
The core issue here is that Metricsgraphics.js expects date values to be actual Date objects, but the JSON data you're pulling from MySQL is returning date strings (like "2018-04-28..."). Here's how to resolve this step by step:
1. Convert Date Strings to Date Objects in Your Data
First, you need to iterate over your dataset and convert each date string into a JavaScript Date instance. Note that your sample data1 appears to be a nested array ([ [ { ... } ] ]), so you'll want to extract the inner array first if that's the case:
// Assuming data1 is structured as [ [ { "date": "2018-04-28...", ... }, ... ] ] const processedData = data1[0].map(item => { return { ...item, // Convert the date string to a Date object date: new Date(item.date) }; });
If your data is a flat array (not nested), simplify it to:
const processedData = data1.map(item => ({ ...item, date: new Date(item.date) }));
2. Ensure MySQL Outputs a Parseable Date Format
To make sure the date strings from MySQL are reliably parsed by JavaScript's Date constructor, format the date directly in your SQL query using DATE_FORMAT. Use an ISO 8601-compatible format, which is universally supported:
SELECT DATE_FORMAT(your_date_column, '%Y-%m-%dT%H:%i:%sZ') AS date, your_value_column AS value FROM your_table;
This will return dates in the format "2018-04-28T12:00:00Z", which new Date() can parse without issues.
3. Verify the Processed Data
Before passing the data to Metricsgraphics, check that the dates are valid Date objects using console.log:
console.log(processedData[0].date); // Should log a Date object, not a string
If you see Invalid Date in the console, double-check your SQL date formatting or the original date string values.
4. Use the Processed Data in Your Metricsgraphics Call
Finally, pass the processed data to MG.data_graphic:
MG.data_graphic({ title: "My MySQL-Powered Line Chart", description: "Line chart using data pulled from MySQL.", data: processedData, width: 600, height: 200, right: 40, target: '#your-chart-target' });
This should resolve the date display issue, as Metricsgraphics will now recognize the date values as valid date objects and render them correctly on the x-axis.
内容的提问来源于stack exchange,提问作者Maka

