Django API JSONfield fetches an object that I can't use .map to parse and then build a chart
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:
- JSON.parse(data),
- JSON.stringify(data),
- Stripping brackets: const dataArray = data2.data.linechart.replace('[', '').replace(']', '');
- changing data.data.linechart to data.data and then isolating linechart = "[{'index': 129, 'Strategy': 28.893}, {'index': 1304, 'Strategy': 33.331}]"
but I cannot convert the chart data JSON from an Object - without splitting the JSON string into individual characters...
The answer to this one was patience. The answer was simple of course, now that I know how to approach it.
- First, I tested the fetched data and confirmed it was a string with "typeof"
- Next, I found the JSON in the database was single quote, so see the fix for double quotes below - and @Serhii Fomenko pointed out a json.dumps solution that may work as well.
- A text.replace allowed me to JSON.parse - Step 3, which creates an array that .map can work with ... and you are good to go. Hope this helps ...
'''
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);
}