My data
var data = [
{"title":"2013-12-09", "calls_in":"345", "calls_out":"100"},
{"title":"2013-12-08", "calls_in":"125", "calls_out":"97"},
{"title":"2013-12-07", "calls_in":"85", "calls_out":"2"},
{"title":"2013-12-06", "calls_in":"185", "calls_out":"22"},
{"title":"2013-12-05", "calls_in":"74", "calls_out":"419"}
]
arrives from a PHP script in json format as above. I'm using an API namely 'jChartFX', it's basically a javascript graphing library that makes cool charts on the fly with javascript/jquery.
Currently using the data above the library fails to parse it. It fails due to the quotes around the integer values. I need the data to in the format:
var data = [
{"title":"2013-12-09", "calls_in":345, "calls_out":100},
{"title":"2013-12-08", "calls_in":125, "calls_out":97},
{"title":"2013-12-07", "calls_in":85, "calls_out":2},
{"title":"2013-12-06", "calls_in":185, "calls_out":22},
{"title":"2013-12-05", "calls_in":74, "calls_out":419}
]
you see, the integers are NOT wrapped in quotes. How can i do this using jQuery or javascript.
In it's most basic form (working) the full script would look something similar to:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="chartfx.css" />
<script type="text/javascript" src="js/jchartfx.system.js"></script>
<script type="text/javascript" src="js/jchartfx.coreBasic.js"></script>
</head>
<body onload="loadChart()">
<div id="ChartDiv" style="width:600px;height:400px"></div>
<script>
var chart1;
function loadChart(){
chart1 = new cfx.Chart();
chart1.getData().setSeries(2);
chart1.getAxisY().setMin(0);
chart1.getAxisY().setMax(700);
var series1 = chart1.getSeries().getItem(0);
var series2 = chart1.getSeries().getItem(1);
series1.setGallery(cfx.Gallery.Lines);
series2.setGallery(cfx.Gallery.Lines);
var data = [
{"title":"2013-12-09", "calls_in":345, "calls_out":100},
{"title":"2013-12-08", "calls_in":125, "calls_out":97},
{"title":"2013-12-07", "calls_in":85, "calls_out":2},
{"title":"2013-12-06", "calls_in":185, "calls_out":22},
{"title":"2013-12-05", "calls_in":74, "calls_out":419}
]
console.log(data);
chart1.setDataSource(data);
var divHolder = document.getElementById('ChartDiv');
chart1.create(divHolder);
}
</script>
</body>
</html>
Option 1: just call
parseInt()
in the JavaScript on each integer value before passing the data to jChartFX.Option 2: If you can modify the PHP script, encode your JSON like this:
json_encode($arrayContainingTheData, JSON_NUMERIC_CHECK );
Example of option 2:
Result:
{"foo":1,"bar":2}
More info:
json_encode()
JSON_NUMERIC_CHECK
constant