using $.getJSON with JSCharts - javascript

I am a beginner in JSCharts. I'm using $.getJSON to load json files and
with them i want to create charts with JSCharts. I am getting the message:
JSChart: Input data in wrong format for selected chart type
var x= new Array();
$.getJSON('test.json', function(data) {
$.each(data, function(key, val) {
x.push(val[0].abs);
x.push(val[1].ord)
});
});
var myChart = new JSChart('chartcontainer', 'line');
myChart.setDataArray(x);
myChart.draw();
Any ideas how to change to format, so it can be accepted by jscharts?
Even if i pass them as integers they are not accepted.
Json looks like this:
" cordonnee " : [ { " abs " : "45" } ,
{ " ord " : "12" }
],
"autre" : [ { "abs": "68" } ,
{ " ord " : "13" }
]
Thank you

Try to parse the values as Integers.
$.each(data, function(key, val) {
x.push(parseInt(val[0].abs));
x.push(parseInt(val[1].ord));
});

You are providing the data as a 1 dimensional array, it has to be 2 dimensional for a line chart.
$.each(data, function(key, val) {
var y = new Array();
y.push(val[0].abs);
y.push(val[1].ord);
x.push(y);
});
see JSCharts how to use line graphs for more details

Related

how to read datasets from a csv file and use it in the chart.js but only reading the values with a certain timestamp onwards?

I have written a simple python program that makes an api call to a webserver and and save received data in to a csv file.
this is the format of the saved csv file:
11:56:03/13/21,30,70,555.98,1270.41,1,2609
:
12:00:03/14/21,30,70,556.27,1270.35,2,2618
:
01:00:03/14/21,30,70,556.27,1270.35,3,2618
:
01:33:03/14/21,30,70,556.27,1270.35,44,2618
01:34:03/14/21,31,69,558.47,1270.33,12,2619
01:35:03/14/21,31,69,558.34,1270.33,15,2618
01:36:03/14/21,31,69,558.8,1270.33,42,2620
01:37:03/14/21,31,69,559.58,1270.33,472,2625
01:38:03/14/21,31,69,559.58,1270.41,471,2625
01:39:03/14/21,31,69,559.58,1270.41,4761,2625
01:40:03/14/21,31,69,559.58,1270.41,411,2625
this is just a small chunk of data from the file , the api call is being made every one minute and the received data is being saved into the csv file.
What i am trying to do now : i am trying to modify the below Javascript so that it will read only a certain column depending on the current day's timestamp from first column, from the csv file and then use these values as dataset to draw lines on the chart
Javascript:
<script>
var xValues = [1,2,3,4,5,6,7,8,9,10];
new Chart("myChart", {
type: "line",
data: {
labels: xValues,
datasets: [{
data: [860,1140,1060,1060,1070,1110,1330,2210,7830,2478],
borderColor: "red",
fill: false
}, {
data: [1600,1700,1700,1900,2000,2700,4000,5000,6000,7000],
borderColor: "green",
fill: false
}]
},
options: {
legend: {display: false}
}
});
</script>
For Example: let say the day today is 03/14/21 so i want to read the values from 6th column only for current day with timestamp of 01:00 onwards
so from above mentioned chunk of csv data i want only these values [44,12,15,42,472,471,4761,411] into the dataset
i have search everywhere trying to figure out how to do it but i couldnt find the solution to this problem
Copied your data in a github repository to get rid of the CORS Problem.
$(document).ready(function() {
$.ajax({
type: "GET",
url: "https://raw.githubusercontent.com/bmehler/mycsv/main/test.csv",
dataType: "text",
success: function(data) {
processData(data);
}
})
function processData(allText) {
var allTextLines = allText.split(/\r\n|\n/);
console.log('allTextLines', allTextLines);
var length = allTextLines.length;
var splitted;
var dataString = '';
dataString += '[';
for(var i = 0; i < length; i++) {
splitted = allTextLines[i].split(/,/);
console.log('splitted-' + i, splitted);
$.each(splitted, function(key, value) {
if(key == 5) {
console.log('test', value);
dataString += value + ',';
}
});
}
dataString += ']';
var replaced = dataString.replace(",]", "]");
console.log('dataString', replaced);
}
});
console.log: dataString [44,12,15,42,472,471,4761,411]

Loop after Grouped JSON properties

https://jsfiddle.net/MauroBros/f1j0qepm/28/#&togetherjs=qedN5gf7SF
I have a JSON object as follows:
var values = [
{"aname":"account1", "pname":"pname1", "vname":"vname1", "vid":"xxx"},
{"aname":"account2", "pname":"pname2", "vname":"vname2", "vid":"xxx"},
{"aname":"account2", "pname":"pname2", "vname":"vname3", "vid":"xxx"},
{"aname":"account2", "pname":"pname3", "vname":"vname1", "vid":"xxx"},
]
I grouped the "vname" by "pname"
var groups = {};
$.each(values, function(key, values) {
if (!groups.hasOwnProperty(values.pname)) {
groups[values.pname] = {
aname : values.aname,
aid : values.aname,
pname : values.pname,
pid : values.pid,
vid: [],
vname: []
};
}
groups[values.pname].vname.push({
vname: values.vname,
vid: values.vid
});
});
Now I'm trying to loop:
$.each(groups, function(key, groups) {
$('#provider-accounts')
.append($("<optgroup></optgroup>")
.attr("label"," " + groups.aname))
.append($("<optgroup></optgroup>")
.attr("label"," " + groups.pname))
.append($("<option></option>")
.attr("value",groups.vid)
.text(" " + groups.vname[0].vname));
});
ISSUE
The output doesn't return all the options "vname" but only the first one.
How can I insert a loop in the loop. Something like this:
$.each(groups, function(key, groups) {
$('#provider-accounts')
.append($("<optgroup></optgroup>")
.attr("label"," " + groups.aname))
.append($("<optgroup></optgroup>")
.attr("label"," " + groups.pname))
for (var i = 0; i < groups.vname[0].vname.length; i++) {
.append($("<option></option>")
.attr("value",groups.vid)
.text(" " + groups.vname[0].vname[i]));
}
});
Any help?
Thanks
Instead of trying to chain it all into one chain I would create a separate object for the groups first. Then loop through the array and append the various options to the second group and finally append the groups to the select.
This seems to be easier to read also than the chained appends you are currently using
$.each(groups, function(key, groups) {
var $group1 = $("<optgroup>").attr("label", " " + groups.aname);
var $group2 = $("<optgroup>").attr("label", " " + groups.pname);
groups.vname.forEach(function(el) {
$group2.append(new Option(el.vname, el.vid));
});
$('#provider-accounts').append($group1, $group2);
});
#charlietfl's answer does it, and I agree that it would make your code more readable. But if you're still interested if such looping is possible - yes it is. You can use Array .map() for this and append the resulting array of Option elements.
.append(
groups.vname.map( vItem =>
$("<option></option>")
.attr("value",groups.vid)
.text(" " + vItem.vname)
));
I tried to fork your fiddle here: https://jsfiddle.net/b2yg5jvm/

Displaying nested JSON using JQUERY

I currently have a live search box that displays json. However I am having issues in working out how to display the nested JSON.
I am looking to display the images and the "closed" days. Any help would be appreciated. I have include my java-script and a sample of my json.
$('#search').keyup(function() {
var searchTerm = $(this).val();
var myExp = new RegExp(searchTerm, "i");
$.get("shops.php",function(data,status){
var response='';
var json = $.parseJSON(data);
shops = json.shops;
$.each(shops, function(index, item) {
if(item.shop_name.search(myExp) != -1){
response += "<h2>"+item.shop_name+"</h2>";
response += "<h2>"+item.distance_citycentre.driving_miles+"</h2>";
});
}
$("#content").html(response);
});
});
Here is a sample of my JSON.
{"shops": [
{ "shop_name":"tesco",
"distance_citycentre": {
"driving_miles":"1.5",
"driving_minutes":"3"
},
"closed": [
"monday",
"wedensday",
"friday"
],
"images" [
{
"description":"lake",
"id":"1"
},
{
"description":"ocean",
"id":"2"
}
]
},
{"shop_name":"asda", etc.......
Here goes your solution
$(document).ready(function() {
var data = '{ "shops":[{"closed":["monday","wedensday","friday"],"images" :[{"description":"lake","id":"1"},{"description":"ocean","id":"2"}]}]}';
var response='';
var json = $.parseJSON(data);
shops = json.shops;
alert(shops[0].closed[0] + " - "+shops[0].closed[1] + " - " +shops[0].closed[2]);
alert(shops[0].images[0].description + " - "+shops[0].images[0].id);
});
And change the JSON Output if possible, There is a little error near "image"<<-- It requires colon ":" You can find the same working model on [JSfiddle][1]
[1]: https://jsfiddle.net/u6exgn7s/ here
If you're talking about how to access json objects in an array which is in an array, you can access them by using array[0].object.array[0].object.array[0].array[0]
In your example you can select closed day 'monday' by using:
item.shops[0].closed[0];
or friday by using:
item.shops[0].closed[2];
You determine the position in the array by [-number from 0 to infinity-]

displaying json data in javascript not working

I have created a var and passed JSON data(comma seperated values) to it, but when I want to display json data - it only returns null. Here's the code:
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
You can either do it like this:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
or you can do it like this
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
Either way, storing just one object in the list makes this answer a bit redundant unless I show you how to loop over multiple objects.
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
I'm using a mix of jQuery here aswell, which might not be optimal but atleast it serves to show that there are multiple ways to accomplishing what you need.
Also, the forEach() method on arrays is a MDN developed method so it might not be crossbrowser compliant, just a heads up!
If you want pure JS this is one of the ways to go
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
For simple and quick printing of JSON, one can do something like below and pretty much same goes for objects as well;
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
and now to print on screen, a simple for in loop is enough, but please not e, it won't print array instead will print [object Object]. for simplicity of answer, i won't go in deep to print arrays key and value in screen.
Hope that this will be usefull for someone. Cheers!
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}

javascript each - autodetect name of val in (key,val)

I have a JSON file that has more name value pairs than I care to type in. Either lazy or elegant. Instead of using what I have below where I have to type in all the name values pairs there must be a property of val like val.name so not to have to type all the other pairs out. What's the proper terminology to search find the answer? or the code would be nice too :)
This is what I started using when I thought, "crap, I have to type all that *#&#$ out!"
$.each(data, function(key, val) {
items.push(key + val.TimeStamp + val.bandwidth + );
JSON
{
"Router": "HS-DSCS1",
"router_data": [
{
"TimeStamp": "2012/01/01 06:00:00",
"NeighborIP": "192.168.1.1",
"State": "Full",
"Bytes001": "21362.95663",
"Bytes002": "2.67 KB",
"Bytes003": "9887.99707",
"Bytes004": "1.24 KB",
"Bytes005": "Serial0/1/0"
}
]
}
Seems like you're just doing string concatenation. If so ...
$.each(data, function(key, val) {
items.push(key + $.map(val, String).join('') );
});
DEMO: http://jsfiddle.net/ZVDcy/
Or if you're building a new Array, you could do this...
var items = $.map(data, function(val, key) {
return key + $.map(val, String).join('');
});
DEMO: http://jsfiddle.net/ZVDcy/1/
If I'm understanding your question right, just use a for..in.
for (field in val){
// something with val[field]
}

Categories

Resources