Passing MySQL data from flask to JavaScript for Google Charts - javascript

I've already checked out some similar questions here: How can I pass data from Flask to JavaScript in a template?
I'm trying to create a google chart using this example , where my data is coming from a database query, which is then parsed and formatted to be passed through Google's datasource python library, then converted into a json string. From there it is supposed to be passed through a JavaScript function in my HTML file in order to populate the Google Charts table. This last part seems to be causing me trouble. Here is the meat of my function in flask:
description = {"count": ("number", "Count"),"type": ("string", "Type")}
data=[]
rows = cur.fetchall()
# formats MySQL data for JSON string
for row in rows:
js = {'type': row[0], 'count': row[1]}
data.append(js)
# Loading it into gviz_api.DataTable (from Google Charts template)
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
# Create a JSON string. (from google charts template)
json= data_table.ToJSon(columns_order=("type", "count"), order_by="count")
render_template('myhtml.html' , json=json)
at the end of my function in flask, which is then passed through the following JavaScript function in my html file here:
<script>
...
// taken from the Google Charts example
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
var json = '{{ json }}'
function drawTable(json) {
var json_table = new google.visualization.Table(document.getElementById('table_div_json'));
var json_data = new google.visualization.DataTable((json), 0.6);
json_table.draw(json_data, {showRowNumber: true});
}
The chart is not drawn and I am left with only the header for the chart. I don't believe this is an issue with the format of my data or the HTML portion (which I've left out), for it is taken straight from the Google Charts template, so I've been trying to find problems in my JavaScript (which I am fairly new to). Can this string not be passed to the JavaScript function in this fashion? What alternative ways can it be done? Any pointers and suggestions would be great.

Probably have to escape it, something like:
{{json | safe}}

Related

Dinamically populate google chart just using only Javascript

I'm using Google Charts API inside my C# project (using the WebBrowser from CefSharp), and it works with the data hard coded to it, but I'm running into a problem whenever I try to dinamically populate it using data.addRows(). I need to have something simple, like a external csv/json, so it's possible to run inside C# (WebBrowser is really limited and sometimes buggy), but every solution tells me to do that via php server or something more "complex" like that. So, is there a way to populate that chart just using JavaScript and an external file (or something different but viable)?
Thats the code, if useful:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages:["orgchart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
// For each orgchart box, provide the name, manager, and tooltip to show.
data.addRows([['Alice', 'Mike', ''],['Bob', 'Jim', 'Bob Sponge'],['Carol', 'Bob', '']]);
// Create the chart.
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
// Draw the chart, setting the allowHtml option to true for the tooltips.
chart.draw(data, {'allowHtml':true});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
Obs: CefSharp WebBrowser just calls this code above as a normal HTML file and runs it inside the C# application.
Thank you!
I've done something similar, but I've been using the arrayToDataTable() method of the google charts API, but I'm sure this can be done similarly. You will need to lean on C# though. I wanted to be thorough so this is a big one. More than happy to clarify because I'm sure that at least some of this will be poorly worded/confusing.
TLDR
Create a Class to hold your data points and a way to represent them as a list.
In Your Controller class, Create a method that returns a list containing your data points represented as lists. Turn that List of lists into JSON and Post it to a URL endpoint
Read your json data from that endpoint using ajax in the cshtml
Put the read json into your AddRows method.
Party
This will touch on : the .cshtml, the Home Controller, and Wherever you are pulling your data.
Wherever you are pulling your Data
My case is a bit complicated. But basically I have a method that just returns a list of type object that holds these objects, represented as lists. (eg. [<Timestamp>,<Temperature>,<Humidity>])
public class WeatherEntry
{
public string Timestamp { get; set; }
public double TEMPERATURE { get; set; }
public double Humidity { get; set; }
... Other stuff ...
}
If you can generate a list of data points, represented as lists on the c# side, you are in business.
The Controller class
Assuming you are using ASP.net MVC, you'll have a backing controller class that holds your Controlling C#
Once you have a list of type object containing your data points represented as lists, you can make it into JSON pretty easily using Newtonsoft.Json's JSonConvert.SerializeObject() Method as such:
public ActionResult GetChartData_All_Week()
{
var dataPointsList = this.myDataSource.GetMyDataPointList();
var convertedJson = JsonConvert.SerializeObject(dataPointsList, new JsonSerializerSettings()
{
//Not Needed, I just like to throw out any values that are null.
NullValueHandling = NullValueHandling.Ignore
});
return Content(convertedJson);
IMPORTANT We'll be using ajax in the next step, so we need the magical [Route] Attribute above this action result method as such:
Route("Index/Path/To/Post/To")]
public ActionResult GetChartData_All_Week()
All the hard stuff is done now. If you launch your App and visit the route you defined above (For me it is /Index/Charts/All/Week) You should see your JSON data there similar to this:
[["07/04/2020",25.5,44.0],["07/05/2020",25.600000381469727,45.0],["07/06/2020",25.5,44.0],...["07/08/2020",25.5,43.0]]
If You don't then this next part isn't going to work out. Always remember that it is a List of Lists we will need!
The .cshtml, AJAX, and jQuery magic
Most of your chart is already there. If It's working with the sample data as you posted, this will be super ez. inside your drawChart() method, you'll add the following before the data.AddRows() call.
var jsonData = $.ajax({
url:'Index/Path/To/Post/To',
dataType:"json",
async:false,
type:"GET"
}).responseText;
var asJson = JSON.parse(jsonData);
data.AddRows(asJson);
And now you should have it! The page and datasource will require a refresh to chart any new data that is added, but this should give you a dynamically sized list of points. The hardest part that I had was formatting my data as a List of Lists. I would recommend adding a CS List<object> ToList() method to whatever your equivalent to my Weather_Entry class is to put all of the important Data points into a list in order*. That makes it nice and easy to do something like:
public List<object> GetMyDataPointList(){
var myDataPointList = new List<MyDataPointType>();
myDataPointList = this.GetMyListOfDataPoints();
List<object> turnMeIntoJSON = new List<object>();
myDataPointList.ForEach(dp => turnMeIntoJSON.Add(dp.ToList));
return turnMeIntoJSON;
}
Best of Luck!

creating D3 Word Cloud by using an array of json objects instead of reading from json file

I am quite new to D3 and I have a D3 word cloud template that reads from a json file and then creates a word cloud. The part that reads from json file and inputs the keys and values into chart is :
d3.json("testdata.json", data => {
var chart = renderChart()
.svgHeight(600)
.container('#myGraph')
.data({ values: data })
.responsive(true)
.run()
})
What I wish to do is populate this word cloud from an array of json objects that are created by the program dynamically during the program execution that is why I cannot write it into a json file manually.
One of the many codes that I tried to use was this:
test =>{
var chart = renderChart()
.svgHeight(600)
.container('#myGraph')
.data({ values: test})
.responsive(true)
.run()
}
where test is my array of json objects.
The code is working with no errors but it is displaying nothing.
Any help much appreciated !
Fixed! code has to be:
var chart = renderChart()
.svgHeight(600)
.container('#myGraph')
.data({ values: test})
.responsive(true)
.run()

load json data to dataset in d3js

I am having json file like this. It contains some data.
[{\"Frequency\":\"Building 1\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":46,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":32,\"Value1\":26,\"Value2\":12}]},{\"Frequency\":\"Building 2\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":23},{\"Name\":\"food\",\"Value\":34,\"Value1\":33,\"Value2\":12}]},{\"Frequency\":\"Building 3\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":57,\"Value1\":22,\"Value2\":24},{\"Name\":\"food\",\"Value\":42,\"Value1\":16,\"Value2\":11}]},{\"Frequency\":\"Building 4\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":59,\"Value1\":26,\"Value2\":33},{\"Name\":\"food\",\"Value\":44,\"Value1\":26,\"Value2\":35}]},{\"Frequency\":\"Building 5\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":11},{\"Name\":\"food\",\"Value\":48,\"Value1\":26,\"Value2\":3}]},{\"Frequency\":\"Building 6\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":21},{\"Name\":\"food\",\"Value\":47,\"Value1\":26,\"Value2\":24}]},{\"Frequency\":\"Building 7\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":58,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":43,\"Value1\":26,\"Value2\":22}]},{\"Frequency\":\"Building 8\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":2},{\"Name\":\"food\",\"Value\":34,\"Value1\":26,\"Value2\":33}]}]
I want to store this json file into dataset in d3.js. or
I have given all data are static into my code. I want to give these data from json file to d3.js can any one give me example.
my expected result is
dataset = JSON.parse("[{\"Frequency\":\"Building 1\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":46,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":32,\"Value1\":26,\"Value2\":12}]},{\"Frequency\":\"Building 2\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":23},{\"Name\":\"food\",\"Value\":34,\"Value1\":33,\"Value2\":12}]},{\"Frequency\":\"Building 3\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":57,\"Value1\":22,\"Value2\":24},{\"Name\":\"food\",\"Value\":42,\"Value1\":16,\"Value2\":11}]},{\"Frequency\":\"Building 4\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":59,\"Value1\":26,\"Value2\":33},{\"Name\":\"food\",\"Value\":44,\"Value1\":26,\"Value2\":35}]},{\"Frequency\":\"Building 5\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":11},{\"Name\":\"food\",\"Value\":48,\"Value1\":26,\"Value2\":3}]},{\"Frequency\":\"Building 6\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":62,\"Value1\":26,\"Value2\":21},{\"Name\":\"food\",\"Value\":47,\"Value1\":26,\"Value2\":24}]},{\"Frequency\":\"Building 7\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":58,\"Value1\":26,\"Value2\":22},{\"Name\":\"food\",\"Value\":43,\"Value1\":26,\"Value2\":22}]},{\"Frequency\":\"Building 8\",\"Data\":[{\"Name\":\"Medicine\",\"Value\":48,\"Value1\":26,\"Value2\":2},{\"Name\":\"food\",\"Value\":34,\"Value1\":26,\"Value2\":33}]}]");
inside the bracket my data should be come i dont know how to do this can any tell me how to do this.
before i tried this but it is not working.
d3.json("D3json.json", function(error, data) {
var datas = data;
})
here is my jsfiddle example: Click here to see the example
Thanks
Vinoth S
If I understood your question correctly, you are trying to dynamically load JSON data in contrast to having it hard-coded in your file.
Here is an example how to do it: http://bl.ocks.org/Jverma/887877fc5c2c2d99be10
In general, you have to execute the drawing part after you successfully loaded the data (within the callback function of d3.json())

Integrating JSON data to highcharts

Lets say I want to use JSON code from one site, particular this one, "http://coinmarketcap.com/static/generated_pages/currencies/datapoints/boostcoin-main.json", to integrate it for my highcharts. As I have seen this has following values: x_min, x_max and price_data. How can I make highcharts on my site using this JSON data? Any help with this?
Look at this example and how it uses JSON code and notice how the JSON data should be, because it changes with every chart type: http://jsfiddle.net/highcharts/YWVHx/
$.getJSON('THE LINK TO YOUR FILE',
function(data) {
// Create the chart
$('#container').highcharts(
...
data : data,
...
);
});
EDIT: More information about working with data

How can I use my data from a JSON string to populate dimple d3.js line chart?

My objective is to get data from database and use it to populate a dimple js line chart.
I am using JSON to carry the data from back-end. Below is the code from my servlet going to http request/respose.
String sql2 = "select a,date from table order by date";
JSONArray list = new JSONArray();
DataDAOImpl rdao = new DataDAOImpl();
list = rdao.getData(sql2);
req.setAttribute("line", list.toJSONString());
WebUtil.forward(req, resp, this, "/test/linechart.jsp");
And my code in jsp is as below. It is inside a javascript tag. The chart is not rendering although the data is available in JSP. Also this is running on local web server. Please advice what I am missing. I have to generate several reports and this is my proof of concept.
//script type="text/javascript">
var data = '${line}';
var chart = new dimple.chart(svg, data);
chart.setBounds(100, 200, 505, 305);
chart.addCategoryAxis("x", "date");
chart.addMeasureAxis("y", "a");
chart.addSeries(null, dimple.plot.line);
chart.draw();
///script>
have you tried JSON.parse('${line}');?
I'm not familiar with your exact case but I believe that will turn a string containing JSON into JSON. Is there any console error?

Categories

Resources