如何将JSON中年份值转为单引号包裹字符串以适配Morris折线图
I see the issue here - Morris.Area isn't picking up your numeric year values because it expects string-based x-axis labels in this scenario. Let's resolve this by converting those numeric years to quoted strings, either by adjusting your JSON source or handling it dynamically in your JavaScript code.
Target JSON Format (with String Years)
Here's the corrected JSON where each year value is wrapped in quotes (string type):
[ {"year":"2008","value":20,"sales":10}, {"year":"2010","value":10,"sales":20}, {"year":"2015","value":5,"sales":30}, {"year":"2020","value":25,"sales":40}, {"year":"2025","value":30,"sales":50}, {"year":"2030","value":40,"sales":60}, {"year":"2035","value":60,"sales":70} ]
Dynamic Conversion in JavaScript (If You Can't Modify the Original JSON)
If you can't adjust the JSON coming from your backend, you can convert the year values to strings right after parsing the response. Here's the updated Onsuccess function:
function Onsuccess(response) { var str1 = JSON.parse(response.d); // Convert numeric year values to strings str1.forEach(item => { item.year = item.year.toString(); // Convert number to string }); Morris.Area({ element: 'morris-area-chart', data: str1, xkey: 'year', // Now this will correctly pick up the string year values ykeys: ['sales'], labels: ['value'], pointSize: 3, fillOpacity: 0, pointStrokeColors:['#55ce63', '#009efb', '#2f3d4a'], behaveLikeLine: true, gridLineColor: '#e0e0e0', lineWidth: 3, hideHover: 'auto', lineColors: ['#55ce63', '#009efb', '#2f3d4a'], resize: true }); }
Why This Works
Morris.js relies on string values for x-axis labels when using xkey - numeric values can sometimes fail to map correctly to the chart's x-axis. By converting each year from a number to a string, we ensure the library can properly read and display the year values on your area chart.
内容的提问来源于stack exchange,提问作者Kiran das vakkil

