How to dynamically link json data to chart.js - javascript

I am trying to create a chart using json data. Currently I have the data within my script, but I would like to link it to a separate .json file within the project folder.
This is what I have currently:
var jsonfile = {
"jsonarray": [{
"name": "Joe",
"age": 12
}, {
"name": "Tom",
"age": 14
}]
};
var labels = jsonfile.jsonarray.map(function(e) {
return e.name;
});
var data = jsonfile.jsonarray.map(function(e) {
return e.age;
});
var ctx = document.getElementById("chart");
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'Graph Line',
data: data,
backgroundColor: 'rgba(0, 119, 204, 0.3)'
}]
}
});
Ideally, I would like the json data to be in a separate file so that it can be dynamically saved.
Thanks :)

You can use the fs module to read and write to a file
var fs = require('fs');
var jsonfile = fs.readFileSync('the/path');
//if you want to write to the file I gave you a link that shows you the way
For more information about the fs module you can check File System | Node.js v12.6.0 Documentation.
You may need to pass by JSON.stringify and JSON.parse to save your object as a string in the file and to parse the string back to an object while reading the file.
Another manner that you may consider is lightweight javascript databases such as IndexedDB which is an embedded database in the browser side, or other databases such as neDB if you want to persist data especially with an electron app.

Have many way to use with your wish
var data = {"a" : "b", "c" : "d"};
then
<script src="data.js" ></script>
or
var json = require('./data.json');
or
$.getJSON("data.json", function(json) {
console.log(json);
});
Good luck!

Related

chartjs time cartesian axis adapter and date library setup

I am trying to implement this tutorial and could not get it done. https://www.chartjs.org/docs/latest/axes/cartesian/time.html
Input: list of objects with (time,value) attributes. Time is Integer that means unix time in seconds; value is Float.
The tutorial says "Date Adapters. The time scale requires both a date library and a corresponding adapter to be present. Please choose from the available adapters".
Date library, date-fns: https://github.com/date-fns/date-fns
Question 1. how to install/include the date-fns library? The documentation says "npm", but I think it is only for Node.js, but I have a Django project, Ubuntu. If I just download the zip, there is a bunch of files inside.
Adapter, chartjs-adapter-date-fns https://github.com/chartjs/chartjs-adapter-date-fns.
Question 2. how to install the fns adapter? The documentation says "npm", but I have a Django project, Ubuntu. BUT, if I include <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>, I feel it is enough.
Question 3. after installing adapter and date library, how to fix the script below to make the plot work (Time Cartesian Axis)? I think it is all about updating line point["x"] = elem.time; to convert a unix time to some appropriate type.
HTML
<canvas id="myChart"></canvas>
JS
let points = [];
for(let elem of objs) {
point = {};
point["x"] = elem.time;
point["y"] = elem.value;
points.push(point);
}
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: points,
// Configuration options go here
options: {
responsive: false,
scales: {
x: {
type: 'time',
}
}
}
});
Installing all the 3 required libs can indeed be done using script tags, see live example underneath.
The reason your data doesnt show is because chart.js doesnt expect a data array in the data field. In the data field it expects an object with at least a key for all the datasets which is an array and an optional labels array, but since you are using object format for your data the labels array is not neccesarry.
Each dataset has its own label for the legend and in the dataset object you configure the data array in the data field. See live example:
const options = {
type: 'line',
data: {
datasets: [{
label: '# of Votes',
data: [{
x: 1632664468243,
y: 5
}, {
x: 1632664458143,
y: 10
}],
borderColor: 'pink'
}]
},
options: {
scales: {
x: {
type: 'time'
}
}
}
}
const ctx = document.getElementById('tt').getContext('2d');
new Chart(ctx, options);
<canvas id="tt"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

How to assign external json file as variable in other file

I currently have some Javascript on a page template which manages some JSON data. The way I have it configured currently, the JSON data is assigned to a variable right on the page template. What I would like to do is move the JSON to an external .json file and still be able to use my variable on the page template. Currently it looks like this:
var data = [{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}];
What I would like to do is create a file called data.json and then assign it as the data variable on my page template.
data.json:
{
"fruit": "Apple",
"size": "Large",
"color": "Red"
}
Page template:
var data = 'data.json';
How can I accomplish this?
Load your json in dynamic way using e.g. fetch
async function start() {
let url = 'my.json'
var data = await (await fetch(url)).json();
// ...
}
start();

How to export json object into excel using javascript or jquery?

I wanted to export my json object into excel file. I have searched in Google and tried the following, but I am unable to get or export my object data into excel file on clicking of button, it is downloading but without any columns/data(i.e empty file is downloading).
I am not sure what is the problem, Please someone help me regarding this. Thanks in advance !
Created Plnkr.
html:
<div id="dvjson"></div>
<br><button type="button" id='DLtoExcel'>
Download CSV
</button>
js:
$(document).ready(function(){
//if I give below json object, file is downloading with the columns/data and hence it is fine
//var testjsondata = [{"number":123}];
//if I give like below object, empty file is downloading, not having any data
//it is not working //it should also work
//var testjsondata = {"number": 123}//it is not working //it should also work
//and the following object format also should work
var testjsondata = {
"test": {
"name": "abc",
"address": [{
"number": "12345",
"street": "xyz"
}]
},
"mynumber": 12
};
var $btnDLtoExcel = $('#DLtoExcel');
$btnDLtoExcel.on('click', function () {
$("#dvjson").excelexportjs({
containerid: "dvjson"
, datatype: 'json'
, dataset: testjsondata
, columns: getColumns(testjsondata)
});
});
console.log(testjsondata);
});
Any other solutions or libraries also welcome, my json object is plain type, not any array type.

Highcharts csv data loading and parse into separate array and json

First post here, and I am quite new to javascript so hopefully explaining my question correct. I am trying to process data from a csv file into JSON and create a Highcharts chart with this data, but don’t know where to start. I looked into a lot of answers but they do not fully seem to address my question. My goal is to produce a Highcharts stacked area chart from a csv file located on the same server.
The Highcart code I now have uses a single array for the x-axis named categories (years in this example):
var categories = [ '1850', '1900', '1950', '2000'];
and a JSON for the dataseries: var data = [{
name: 'Line1',
data: [116, 127, 131, 143]
}, {
name: 'Line2',
data: [206, 217, 221, 233]
}, {
name: 'Line3',
data: [303, 313, 326, 338]
}]
Most datasets and charts used in previous answers use a csv file with vertical representation of time series where the second column is used for the data. For instance the daily stockprice of last year.
But the data.csv file I am planning to use looks like this:
Lines, ‘1850’, ‘1900’, ‘1950’, ‘2000’
Line1, 116, 127, 131, 143
Line2, 206, 217, 221, 233
Line3, 303, 313, 326, 338
I was thinking about using a $.get function like this:$.get(‘data.csv’, function (csvfile) { //existing code for creating the chart… } and create a function for parsing the csv data into the variable Data and the variable Categories. But I have no clue how to do this..
The basic code (with hardcoded data) in this: JSfiddle
Does someone have an idea which javascript code I need to parse CSV data into the json/data of the Highcharts graph ?
EDIT:
I use this code to read the csv data through an ajax call and an process the received data:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(data) {
var table = data.split("\n").map(line => line.split(","));
var categories = table[0].slice(1);
var data = table.slice(1).map(a => ({"name": a[0], "data": a.slice(1)}));
console.log(data);
console.log(categories);};
The data is received correct but the array consists of strings instead of numbers. Which part do i need to modify in the processData function to get number datatype?
Assuming that your csv data arrives in the form of "Lines,1850,1900,1950,2000\nLine1,116,127,131,143\nLine2,206,217,221,233\nLine3,303,313,326,338" then in order to construct your categories and data arrays you might do as follows;
var csvData = "Lines,1850,1900,1950,2000\nLine1,116,127,131,143\nLine2,206,217,221,233\nLine3,303,313,326,338",
table = csvData.split("\n").map(line => line.split(",")),
categories = table[0].slice(1),
data = table.slice(1).map(a => ({"name": a[0], "data": a.slice(1)}));
console.log(categories);
console.log(data);
And if you would like to receive the array contents as number type instead of string you may do as follows;
var csvData = "Lines,1850,1900,1950,2000\nLine1,116,127,131,143\nLine2,206,217,221,233\nLine3,303,313,326,338" ,
table = csvData.split("\n").map(line => line.split(",")),
categories = table[0].slice(1).map(e=>e*1),
data = table.slice(1).map(a => ({"name": a[0], "data": a.slice(1).slice(1).map(e=>e*1)}));
console.log(categories);
console.log(data);

To create piechart in highcharts

Below is my JSON format of data from which I want to create a pie chart in highcharts..
{
"title": {"text": "Pie"},
"series":
[
{
"type": "pie",
"name": "Actual",
"data":
[
[
"Salesgrowth",
45
],
[
"marketshare",
26.8
]
]
}
]
}
This is valid JSON , I am getting this output from Web Service, when I call this service and evoke this method to run this JSON output to create pie then I get the error as follows,
Uncaught TypeError: Cannot set property 'renderTo' of undefined
Below is the JQuery function that I make use to call my file where I stored this JSON output from my web service,
function loadJson() {
$(document).ready(function () {
//alert("inside");
var chart;
var seriesData;
$.getJSON("val1.json", function (data) {
var chartoptions = data;
chartoptions.chart.renderTo = 'container';
chart = new Highcharts.Chart(chartoptions);
});
});
},
and this function runs well with other kind of charts like bar graph,line graph and column graph...tested with all kinds of graphs, I am facing problem only with pie chart...any help will be greatly appreciated
---------Updated question------
Below is my JSON output I have changed in order to get values
{
"title":{"text":"Financial"},
"chart":{"type":"pie"},
"series":
[ {"name":"Actual-Market Share","data":["Market Share",30]},{"name":"Actual-Market Share","data":["Sales Growth",70]}]}
and below is the output I am getting,
I am not able to identify what I am exactly messing with...Any idea will be of great help...
----------Updated output-----------
{
"legend":{"enabled":"true"},
"title":{"text":"Financial"},
"chart":{"type":"pie"},
"series":[{"name":"Actual","data":[{"str":"Market Share","flo":20}]},
{"name":"Actual","data":[{"str":"Sales Growth","flo":30}]},
{"name":"Actual","data":[{"str":"Operating Profit","flo":40}]},
{"name":"Actual","data":[{"str":"Gross Margin %","flo":10}]}]}
Your json doesn't include a chart object, so setting chart.renderTo won't work.
If you can change the webservice, get it to add the following to your json:
chart: {
},
If you can't change the back end, you can change your javascript to add the chart object before setting renderTo:
$.getJSON("val1.json", function (data) {
var chartoptions = data;
if (typeof chartoptions.chart === 'undefined') {
chartoptions.chart = {};
}
chartoptions.chart.renderTo = 'container';
chart = new Highcharts.Chart(chartoptions);
});

Categories

Resources