Reputation: 329
I have a Django serialized API field that contains database JSONfield data that creates a chart (this data is confirmed to work on my Flask backend), but I can't use the same data taken from a Django API
'''
// data.data.linechart: "[{'index': 129, 'Strategy': 28.893}, {'index': 1304, 'Strategy': 33.331}]"
fetch(url)
.then(response => response.json())
.then(data => {
var dataArray = Object.keys(data.data.linechart).map(function(key) {
return [key, data.data.linechart[key]];
});
// Convert the array of key-value pairs to a format that supports map
var mapData = dataArray.map(function(item) {
return { index: item[0], Strategy: item[1] };
});
const series = [
{
name: 'Strategy',
data: mapData
}
];
//Apex Chart
var optionsChart = {
series: [{
name: 'New Data',
data: series
}],
What am I missing here?
Fetch is pulling serialized API data as an object - and the conversion above isn't working. Have others seen the same problem?
I have tried:
but I cannot convert the chart data JSON from an Object - without splitting the JSON string into individual characters...
Upvotes: 0
Views: 34
Reputation: 329
The answer to this one was patience. The answer was simple of course, now that I know how to approach it.
'''
fetch(url)
.then(response => response.json())
.then(data => {
console.log("data", data);
console.log("jsonchartData", data.data.jsonchartData);
// test that JSONdata is a string
console.log("jsonchartData tests", typeof data.data.jsonchartData, typeof JSON.stringify(data.data.jsonchartData));
var lineChartData = data.data.jsonchartData;
// parsing this string requires double-quotes, not single
lineChartData = lineChartData.replace(/'/g, '"');
console.log('JSON string:', lineChartData);
try {
var parsedData = JSON.parse([lineChartData]); // this creates an array that can be mapped
console.log('Parsed data:', parsedData);
if (Array.isArray(parsedData)) {
console.log('Parsed data is an array');
var xLabel = parsedData.map(d => d.xLabel);
var yLabel = parsedData.map(d => parseFloat(d.yLabel.toFixed(2)));
console.log("xLabel", xLabel);
console.log("yLabel", yLabel);
} else {
console.log('Parsed data is not an array');
}
} catch (e) {
console.error('Error parsing JSON:', e);
}
Upvotes: 0