I am trying to display JSON data on a doughnut chart using chartJS. My issue is that it will only display one piece of data from the JSON. How do I get all pieces of data to display? Code is below:
const xmlhttp = new XMLHttpRequest();
const url = 'https://api.npoint.io/c189874f4d8f7c14d816';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
const datapoints = JSON.parse(this.responseText);
var labels1 = datapoints.activePositions.map(function(e) {
return e.positions;
});
var data1 = datapoints.activePositions.map(function(e) {
return e.holders;
});
const insitutionalholders = document.getElementById('institutional_activepositions_piechart').getContext('2d');
const insitutionalholdersforstock = new Chart(insitutionalholders, {
type: 'doughnut',
data: {
labels: labels1,
datasets: [{
label: 'yooooo',
data: data1,
backgroundColor: [
'rgba(0, 255, 255, 0.2)'
],
borderColor: [
'rgba(0, 255, 255, 1)'
],
borderWidth: 2.5
}]
}
});
}
}
Below is my JSON data (the data is need is from "activePositions"):
{
"activePositions": [
{
"positions": "Increased Positions",
"holders": "1,799",
"shares": "201,837,184"
},
{
"positions": "Decreased Positions",
"holders": "2,313",
"shares": "226,754,389"
},
{
"positions": "Held Positions",
"holders": "306",
"shares": "8,979,550,845"
},
{
"positions": "Total Institutional Shares",
"holders": "4,418",
"shares": "9,408,142,418"
}
],
"newSoldOutPositions": [
{
"positions": "New Positions",
"holders": "122",
"shares": "55,880,226"
},
{
"positions": "Sold Out Positions",
"holders": "74",
"shares": "8,818,741"
}
]
}
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="draftfortesting.css">
</head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<body>
<div class="myChartDiv">
<canvas id="institutional_activepositions_piechart"></canvas>
</div>
</body>
<script src="AAPLpiechart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
What's weird to me is that the data that shows is the third piece inside the JSON, so I'm not sure why that's happened.
The issue seems to be related to the value of holders field of data points.
The are not numbers having the "comma" (for instance "holders": "1,799",)
You could try to remove the comma and parsing as float:
var labels1 = datapoints.activePositions.map(function(e) {
return e.positions;
});
var data1 = datapoints.activePositions.map(function(e) {
return parseFloat(e.holders.replace(',','')); // remove comma
});
EDIT: to remove the "total" item:
const activePositions = datapoints.activePositions.filter(e => !e.positions.startsWith('Total'));
var labels1 = activePositions.map(function(e) {
return e.positions;
});
var data1 = activePositions.map(function(e) {
return parseFloat(e.holders.replace(',',''));
});
Related
I've been continuing my work on a drag and drop page that will parse and display the json data.
I was able to parse the .json file and showed it in console but at the end there is an error showing up (Please refer on the screenshot below). Did I miss anything from my code? Thank you in advance!
JSFiddle : https://jsfiddle.net/vy19a7sf/2/
(function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondrop = function(event) {
event.preventDefault();
this.className = "dropzone";
console.log(event.dataTransfer.files[0]);
var fileInput = document.getElementById("dropzone");
var fileDisplayArea = document.getElementById("displayarea");
var file = event.dataTransfer.files[0]
var textType = "";
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(read) {
// fileDisplayArea.innerText = reader.result;
var json = reader.result;
for(var num = 0; num < json.length; num++) {
obj = JSON.parse(json);
// console.log(obj["value"][num]);
console.log(obj["value"][num]["changesetId"]);
console.log(obj["value"][num]["author"]["displayName"]);
console.log(obj["value"][num]["createdDate"]);
console.log(obj["value"][num]["comment"]);
}
}
reader.readAsText(file);
}
else {
// fileDisplayArea.innerText = "File not supported!";
console.log("File not supported!")
}
}
dropzone.ondragover = function() {
this.className = "dropzone dragover";
return false;
};
dropzone.ondragleave = function() {
this.className = "dropzone";
return false;
};
}())
.dropzone {
display: flex;
line-height: 300px;
justify-content: center;
border: 2px dashed #ccc;
color: #ccc;
}
.dropzone.dragover {
border-color: #000;
color: #000;
}
.displayarea {
height: 200px;
width: 100%;
color: #000;
padding: 20px;
background-color: #e7e7e7;
overflow-x: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css" />
<link rel="stylesheet" href="/css/styles.css" />
<link rel="stylesheet" href="/changesets/css/styles.css" />
<title>Code Metrics Tool</title>
</head>
<body>
<header>
<div>
Code Metrics Tool
</div>
</header>
<main>
<h2>Changesets</h2>
<div class="dropzone" id="dropzone">Drop .json files here to convert</div>
</main>
<footer>
</footer>
<script src="/changesets/js/dragdrop.js"></script>
</body>
</html>
SCREENSHOT Console log was successfully printed, but at the end there is an error showing up
JSON File
{
"count": 2,
"value": [
{
"changesetId": 1456,
"url": "https://.../changesets/1456",
"author": {
"displayName": "--",
"url": "https://.../0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"id": "0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=0e79980d-2df8-47b2-9aa3-4a7a118f1c90"
},
"checkedInBy": {
"displayName": "--",
"url": "https://.../0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"id": "0e79980d-2df8-47b2-9aa3-4a7a118f1c90",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=0e79980d-2df8-47b2-9aa3-4a7a118f1c90"
},
"createdDate": "2018-02-28T11:20:36.52Z",
"comment": "fixed problems",
"commentTruncated": true
},
{
"changesetId": 1451,
"url": "https://.../changesets/1451",
"author": {
"displayName": "--",
"url": "https://.../f62e6531-cb28-6ebb-bb5c-1663549c6165",
"id": "f62e6531-cb28-6ebb-bb5c-1663549c6165",
"uniqueName": "--",
"imageUrl": "https://.../identityImage?id=f62e6531-cb28-6ebb-bb5c-1663549c6165"
},
"checkedInBy": {
"displayName": "--",
"url": "https://.../f62e6531-cb28-6ebb-bb5c-1663549c6165",
"id": "f62e6531-cb28-6ebb-bb5c-1663549c6165",
"uniqueName": "--",
"imageUrl": "https:///identityImage?id=f62e6531-cb28-6ebb-bb5c-1663549c6165"
},
"createdDate": "2018-02-26T11:47:42.233Z",
"comment": "Added an item",
"commentTruncated": true
}
]
}
As Patrick Evans commented, json.length is not the length of the array in "value".
You also don't want to use obj = JSON.parse(json) inside that loop, you only need to parse it once.
To solve this issue you described, you need to get the actual ids inside the "value" array.
let valueArray = obj.value;
valueArray.forEach(function(vel){
console.log(vel.changesetId);
console.log(vel.author);
//etc..
});
I am a complete beginner so be easy, I have Json codein a URL Link on Amazon AWS and I want to be able to fetch the data and output it to a table on a HTML page can you help me plz. As you can see below the html code, the JS code and sample information I want to pull from the data in the JS URL link
Code below
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="http://fonts.googleapis.com/css?family=Fjalla+One|Cantarell:400,400italic,700italic,700" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="styles.css">
<title>Convert JSON Data to HTML Table Example</title>
<style>
table, th, td
{
margin:10px 0;
border:solid 1px #333;
padding:2px 4px;
font:15px Verdana;
}
th {
font-weight:bold;
}
</style>
</head>
<body>
<TITLE>"Country information"</TITLE>
<h2>Country information </h2>
<section class="content">
<div class="row">
<div class="box">
<div class="box-body">
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
</div>
</div>
<script>
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('https://url.json', function(err, data) {
if (err != null) {
console.error(err);
} else {
var text = `Name: ${data.name}
area: ${data.area}
borders: ${data.borders}`
console.log(text);
}
});
`Sample json file on url I want to display in HTML
{
"name": "Angola",
"altSpellings": [
"AO",
"República de Angola",
"ʁɛpublika de an'ɡɔla"
],
"area": 1246700,
"borders": [
"COG",
"COD",
"ZMB",
"NAM"
],
"callingCodes": [
"244"
],
"capital": "Luanda",
"currencies": [
"AOA"
],
"demonym": "Angolan",
"flag": "https://en.wikipedia.org/wiki/Flag_of_Angola#/media/File:Flag_of_Angola.svg",
"ISO": {
"alpha2": "AO",
"alpha3": "AGO"
},
"languages": [
"pt"
],
"latlng": [
-12.5,
18.5
],
"nativeName": "Angola",
"population": 24383301,
"region": "Africa",
"subregion": "Middle Africa",
"timezones": [
"UTC+01:00"
],
"translations": {
"de": "Angola",
"es": "Angola",
"fr": "Angola",
"ja": "アンゴラ",
"it": "Angola"
},
"wiki": "http://en.wikipedia.org/wiki/angola",
"hemisphere": [
"Southern",
"Eastern"
]
},`
I use something like this for building a html table out of JSON using JS
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
_table_.classList.add('table')
function buildHtmlTable(arr) {
var table = _table_.cloneNode(false),
columns = addAllColumnHeaders(arr, table);
for (var i=0, maxi=arr.length; i < maxi; ++i) {
var tr = _tr_.cloneNode(false);
for (var j=0, maxj=columns.length; j < maxj ; ++j) {
var td = _td_.cloneNode(false);
cellValue = arr[i][columns[j]];
td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
function addAllColumnHeaders(arr, table)
{
var columnSet = [],
tr = _tr_.cloneNode(false);
for (var i=0, l=arr.length; i < l; i++) {
for (var key in arr[i]) {
if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
columnSet.push(key);
console.log(columnSet)
var th = _th_.cloneNode(false);
th.appendChild(document.createTextNode(key));
tr.appendChild(th);
}
}
}
table.appendChild(tr);
return columnSet;
}
then I run this with the returned JSON:
document.getElementById('yourDIV').appendChild(buildHtmlTable(res));
build your api request like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response comes through here
}
};
xhttp.open("GET", "/api/url/", true);
xhttp.send();
Then if you only want to push those 3 objects through to the table, create an array then build the table with those objects (not tested)
// Response comes through here
var obj = []
var data = xhttp.responseText
obj.push(data.name, data.area, data.borders)
document.getElementById('yourDIV').appendChild(buildHtmlTable(data));
Check out this JSfiddle example I did: https://jsfiddle.net/7dvudr5q/5/
I have a map of this form
Object{485:Array[4],2072:Array[4],9665:Array[3]...}
I would like to display a chart per key.
I have an example which is similar to what i'm looking for and i tried to display my values in many charts : In this example, my key is : car_id
First step : sort my array to get a map with my keys. It works fine. But the second one is not working... I would like to display a chart per data based on car_id and per panel bootstrap...
What am I doing wrong ?
Thank you
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
</head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript --><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.min.js"></script>
<script src=" https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.0/Chart.min.js"></script>
<body >
<div >
<div class="panel panel-default">
<div class="panel-heading">Panel heading without title</div>
<div class="panel-body">
<canvas id="myChart" width="400" height="400"></canvas>
</div>
</div>
</div>
</body>
<script>var json = {
'cars': [{
"car_id": "1",
"price": "925",
"full_option": "EEEE"
}, {
"car_id": "1",
"price": "990",
"full_option": "DDDDD"
}, {
"car_id": "2",
"price": "500",
"full_option": "FFF"
}, {
"car_id": "2",
"price": "900",
"full_option": "GGGGGGG"
}, {
"car_id": "4",
"price": "900",
"full_option": "JJJ"
}]
};
var car_array = json.cars.reduce((prev, t, index, arr) => {
if (typeof prev[t.car_id] === 'undefined') {
prev[t.car_id] = [];
}
prev[t.car_id].push(t);
return prev;
}, {});
Object.keys(car_array).forEach(i => {
var array_of_cars_with_same_id = car_array[i];
for (var i=0; i<=array_of_cars_with_same_id.length-1;i++){
console.log(array_of_cars_with_same_id[i].price);
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [array_of_cars_with_same_id[i].full_option],
datasets: [{
label: '# of Votes',
data: [array_of_cars_with_same_id[i].price]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
console.log("AAAAAAAAAAAAA");
});
</script>
There are a couple of problems with your code.
First, you are only using a single canvas element. Each chart needs its own canvas element. Because of this every chart you add simply renders on top of the prior chart.
At a minimum, you have to give each item a new canvas. You could change your code to accomplish that.
Change the root element for the charts to a basic <div> element that you will append the charts to.
<div class="panel-body">
<div id="chart-holder"></div>
</div>
I would create a variable to hold the cart count, and the root element.
var chart_holder = $('#chart-holder');
var chart_count = 0;
Change the for loop to use these new variables.
for (var i = 0; i <= car_type.length - 1; i++) {
chart_holder.append('<canvas id="myChart' + chart_count + '" width="400" height="400"></canvas>')
var ctx = $("#myChart" + chart_count);
var data = [];
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [car_type[i].full_option],
datasets: [{
label: '# of Votes',
data: [car_type[i].price]
}]
},
options: chart_opts
});
chart_count++;
}
This will create a new chart for each object in each array.
I created a fiddle to demonstrate.
Based on the data, however, I would recommend a different approach. I would create a single chart per unique key, rather than a chart for every element.
You would need to parse each array to pull out labels and data for each chart. Here is an example that would get that data out of each array. There is a variable to capture the data for the chart and the labels for the chart.
var car_data = [], car_labels = [];
for (var i = 0; i <= car_type.length - 1; i++) {
car_data.push(car_type[i].price);
car_labels.push(car_type[i].full_option);
}
We can pass car_data and car_labels to the Chart.js initialization.
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: car_labels,
datasets: [{
label: 'Car Type ' + ct,
data: car_data
}]
},
options: chart_opts
});
Here is a fiddle to demonstrate a single chart per car_id.
I am getting a json data from rest api and i want to use it as input to ZingFeed.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
function getNewData()
{
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept:"application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function(data){
var mem = data.mem.size/10000;
return mem/10000;
//$("#processInfo").append(data.mem.size);
//$("#processInfo").append(" ")
}
});
//return parseInt(memSize);
}
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
var tick = {};
// tick.plot0 = parseInt(10 + 900 * Math.random(), 10);
tick.plot0 = parseInt(getNewData());
//tick.plot0 = parseInt(1);
callback(JSON.stringify(tick));
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>
</html>
It is working fine when seen in firebug.The data (i.e mem in this case is really huge, so i have divided it twice before assigning it to tick.plot0).
After getting assigned to tick.plot0 .. it shows Nan when hovered over in the developer tools.
Could you help me plotting these huge values in ZingFeed Charts
Thanks in advance
The issue here is the nature of asynchronous functions in Javascript. Returning the data from AJAX doesn't work the way you've attempted above. You can read more about it here.
Here's a working solution.
I work on the ZingChart team. Let me know if you have other questions about the ZingChart library.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function (data) {
var mem = data.mem.size/10000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
}
});
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>
my graph didn't load up. I try to parse JSON from an JSP page to HTML page with javascript.
I don't know what is the problem. This is the details :
My HTML Page :
<!DOCTYPE html>
<html>
<head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var obj="";
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url : 'getDataGlucose.jsp',
dataType:'json',
success : function(glucoseData) {
obj = JSON.stringify(glucoseData)
alert('Pass? : '+obj);
},
error : function(xhr, type) {
alert('server error occoured')
}
});
var google_data = {
"cols": [{
"type": "number"
}, {
"type": "number"
}],
rows: []
};
for (var i = 0; i < obj.length; i++) {
google_data.rows.push({
c: [{
v: obj[i].xValue
}, {
v: obj[i].glucose
}]
});
}
var data = new google.visualization.DataTable(google_data);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {
title: 'Glucose Data Intake',
hAxis: {
title: 'Intake'
},
curveType: 'function',
vAxis: {
title: 'mmHg'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
My generate JSON from JSP page :
[{"glucose":5.5,"xValue":0}, {"glucose":6.2,"xValue":1}, {"glucose":5.8,"xValue":2}, {"glucose":7,"xValue":3}, {"glucose":6,"xValue":4}, {"glucose":7.5,"xValue":5}, {"glucose":6,"xValue":6}, {"glucose":5.5,"xValue":7}, {"glucose":6,"xValue":8}, {"glucose":5.8,"xValue":9}]
Found my way out. I changed from :
obj = JSON.stringify(glucoseData);
to
obj = eval('(' + JSON.stringify(glucoseData) + ')');