jQuery Flot graph not loading (JSON data) - javascript

I'm having the following issue while using Flot for a graph. The input for the graph is JSON, retrieved from a server.
The ajax call to get the data is:
$.ajax({
url: 'graphdata.do',
dataType: 'json',
success: function (retData) {
renderGraph(retData);
}
});
And the renderGraph function:
function renderGraph(datasets)
{
var data = [];
console.log(datasets);
$('.cbScenarioSelected').each(function(index) {
if($(this).is(':checked')){
var id = $(this).prop("id"); //this works, right id is returned
data.push(datasets[id]);
}
});
$.plot($("#graph1"), data, {
yaxis: { min: 0 },
xaxis: { tickDecimals: 0 }
});
}
The data returned from the server:
{
"1": {
"label": "Name1",
"data": "[[133,64.8000030517578],[134,64.8099975585938],[135,65.0999984741211],[136,66.0699996948242],[137,66.129997253418],[138,66.2600021362305],[139,66.6699981689453],[140,66.9400024414063],[141,67.4100036621094],[142,68.0599975585938], [143,68.0800018310547],[144,68.3600006103516],[145,68.8699951171875], [146,69.4899978637695],[147,69.6500015258789],[148,70.0999984741211], [149,70.7400054931641],[150,70.9199981689453],[151,71.1500015258789], [152,71.7000045776367],[153,72.0899963378906],[154,72.4799957275391], [155,73.2700042724609],[156,73.3000030517578],[157,73.4599990844727], [158,73.5100021362305],[159,74.6799926757813],[160,77.5200042724609], [161,77.8399963378906],[162,78.8300018310547]]"
},
"2": {
"label": "Name2",
"data": "[]"
},
"3": {
"label": "Name3",
"data": "[]"
}
}
The graph container is shown, and so are the labels. The lines in the graph are not shown.
Anyone have an idea? I think it has something to do with the quotes around the "data" tag in the returned data, but I have no idea how to fix it.

In your JSON, data part are string because of they are encapsulated with quotes.
In fact, the json should look like (without quotes)
{
"1": {
"label": "Name1",
"data": [
[
133,
64.8000030517578
],
[
134,
64.8099975585938
],
[
135,
65.0999984741211
],
[
136,
66.0699996948242
],
[
137,
66.129997253418
],
...
]
},
"2": {
"label": "Name2",
"data": []
},
"3": {
"label": "Name3",
"data": []
}
}

Related

Read Google Sheet Exported JSON by column name in Apps Script

I'm exploring the use of JSON exported Google Sheets as database for Apps Script.
The fetched url follows the structure:
https://docs.google.com/spreadsheets/d/DOCUMENTID/gviz/tq?tqx=out:json&gid=SHEETID
JSON.json
{
"reqId": "0",
"sig": "000",
"status": "ok",
"table": {
"cols": [
{
"id": "A",
"label": "",
"type": "string"
},
{
"id": "B",
"label": "",
"type": "string"
},
{
"id": "C",
"label": "",
"type": "string"
}
],
"parsedNumHeaders": 0,
"rows": [
{
"c": [
{
"v": "Data 1-1"
},
{
"v": "Data 1-2"
},
{
"v": "Data 1-3"
}
]
},
{
"c": [
{
"v": "Data 2-1"
},
{
"v": "Data 2-2"
},
{
"v": "Data 2-3"
}
]
},
{
"c": [
{
"v": "Emails"
},
{
"v": "Ids"
},
{
"v": "Names"
}
]
}
]
},
"version": "0.6"
}
In this function I'm getting returned an array of values for the C column:
dataArray = [Data 1-3, Data 2-3]
function getRolePermission(databaseUrl) {
let databaseParsed = JSON.parse(UrlFetchApp.fetch(databaseUrl).getContentText().match(/(?<=.*\().*(?=\);)/s)[0]);
let tableLength = Object.keys(databaseParsed.table.rows).length;
let dataArray = [];
for (let i = 0; i < tableLength; i++) {
dataArray.push(databaseParsed.table.rows[i].c[2].v)
}
return dataArray;
}
It works well, but I don't know how to make this function more generic, so I call it with (url, headerName) arguments to get an array with the values of a column. Something like:
function getRolePermission(databaseUrl, headerName) {
// CODE ??
return dataArray;
}
getRolePermission('https://docs.google.com/spreadsheets/d/1lc...', 'Emails')
to get dataArray = [Data 1-3, Data 2-3], so if I change the order of columns I'm still getting the same results.
dataArray.push(databaseParsed.table.rows[i].c[2].v)
You just need to find the index 2 here to make the function more generic. The table.cols should give you the column headers, but it is not doing that because parsedNumHeaders is 0 in your case. To manually set number of headers, use &headers=1. The url should look like:
https://docs.google.com/spreadsheets/d/DOCUMENTID/gviz/tq?tqx=out:json&gid=SHEETID&headers=1
The response then would look like:
{
"reqId": "0",
"sig": "000",
"status": "ok",
"table": {
"cols": [
{
"id": "A",
"label": "Names",
"type": "string"
},
{
"id": "B",
"label": "Ids",
"type": "string"
},
{
"id": "C",
"label": "Emails",
"type": "string"
}
],
"parsedNumHeaders": 1,
"rows": [
{
"c": [
{
"v": "Data 1-1"
},
{
"v": "Data 1-2"
},
{
"v": "Data 1-3"
}
]
},
{
"c": [
{
"v": "Data 2-1"
},
{
"v": "Data 2-2"
},
{
"v": "Data 2-3"
}
]
}
]
},
"version": "0.6"
}
Once you get the headers, you can find the index:
const columnNeeded = databaseParsed.table.cols.findIndex(obj => obj.label === headerName/*"Emails"*/);
Then, use it in your function
dataArray.push(databaseParsed.table.rows[i].c[columnNeeded].v)

put data from json file array in a jquery array

I have a json file array with data
and I want to use it in a jquery array.
My json file is like this;
[{"id":"1","value":"0.00","score":"a"},
{"id":"2","value":"0.00","score":"c"},
{"id":"3","value":"12.56","score":"e"}]
and then my jquery array outcome i want should be like this (but missing the score and value data.
var setup = [
{
"type": "single",
"subtype": {
"type": "Point",
"score": use 'score' of the json file
},
"properties": {
"text": use 'value' of the json file,
"height": 60
}
},
{
"type": "single",
"subtype": {
"type": "Point",
"score": use score of the json file
},
"properties": {
"text": use value of the json file,
"height": 60
}
}
];
Below I made an attemp to set up a jquery array but i am mnot so good in this. I think i have to use a double $each? but how do I make the array?
var setup = [];
// FETCHING DATA FROM JSON FILE
$.getJSON("results.json", function(data) {
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
var test = "";
$.each(value, function(index, obj) {
});
});
setup.push(setup);
});
Thanks in advance :)
You could use Array.prototype.map() method to get the result.
const data = [
{ id: '1', value: '0.00', score: 'a' },
{ id: '2', value: '0.00', score: 'c' },
{ id: '3', value: '12.56', score: 'e' },
];
const ret = data.map((x) => ({
type: 'single',
subtype: {
type: 'Point',
score: x.score,
},
properties: {
text: x.value,
height: 60,
},
}));
console.log(ret);
You can use one each loop and pass the object with the elements you need. Check the below example:
var jsonData = [{
"id": "1",
"value": "0.00",
"score": "a"
},
{
"id": "2",
"value": "0.00",
"score": "c"
},
{
"id": "3",
"value": "12.56",
"score": "e"
}
]
var setup = [];
// FETCHING DATA FROM JSON FILE
$.each(jsonData, function(key, value) {
var test = "";
d = {
"type": "single",
"subtype": {
"type": "Point",
"score": value.score
},
"properties": {
"text": value.value,
"height": 60
}
};
setup.push(d)
});
console.log(setup)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Filling up DataTable with a JSON object

I am having a JSON file with the following values and I am trying to fill the DataTable with the values of the JSON file.
I would like the DataTable to be of the format with 3 columns (Color, Size, Quantity).
An example would be Red, Small, 100 and Red, Medium, 200.
However, these 3 columns are within the JSON object "invSelectionCount" as shown in my JSON file. How do I iterate through the JSON file to manipulate the object within it to fill up the DataTable?
AJAX Call
$.ajax({
'url': 'http://localhost:8080/Retail-war/webresources/products/getProduct/' + productId,
'method': 'GET',
'contentType': 'application/json; charset=utf-8',
'headers': {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')},
}).done( function(data) {
$('#product-inventory-level').DataTable( {
"data": [data],
"columns": [
{ "data": "invSelectionCount"},
{ "data": "invSelectionCount"},
{ "data": "invSelectionCount"}
],
})
})
JSON File
{
"productId": 1,
"originalPrice": 59.9,
"currentPrice": null,
"productStatus": "LISTED",
"discount": null,
"productVol": null,
"invSelectionCount": {
"red=small": 100,
"red=medium": 200
},
}
You can use map on keys of invSelectionCount to return desired object
Object.keys(data["invSelectionCount"]).map(key =>{return {
Color: key.split('=')[0],
Size: key.split('=')[1],
Quantity: data["invSelectionCount"][key]
}})
Run this snippet
let data={
"productId": 1,
"originalPrice": 59.9,
"currentPrice": null,
"productStatus": "LISTED",
"discount": null,
"productVol": null,
"invSelectionCount": {
"red=small": 100,
"red=medium": 200 }
}
$('#product-inventory-level').DataTable({
"columns": [{
"title": "Color",
"data": "Color",
},
{
"title": "Size",
"data": "Size"
},
{
"title": "Quantity",
"data": "Quantity"
}
],
"data": Object.keys(data["invSelectionCount"]).map(key =>{return {
Color: key.split('=')[0],
Size: key.split('=')[1],
Quantity: data["invSelectionCount"][key]
}})
})
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="product-inventory-level"></table>
Try to expand this:
.done( function(data) {
var array = new Array();
Object.keys(json["invSelectionCount"]).forEach(function(key) {
var splitstring = key.split('=');
splitstring[0] -> red
splitstring[1] -> small
json["invSelectionCount"][key] -> 100
array.push({"color": splitstring[0], "size": splitstring[1], "quantity": json["invSelectionCount"][key],});
});
$('#product-inventory-level').DataTable( {
"data": [array],
"columns": [
{ "data": "color"},
{ "data": "size"},
{ "data": "quantity"}
],
})
})

JS How to remove an object from array in a forEach loop?

I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);

How to get these json nested values using angular?

I have this json response:
{
"tags": [
{
"name": "SolarData",
"results": [
{
"groups": [
{
"name": "type",
"type": "number"
}
],
"attributes": {
"customer": [
"Acme"
],
"host": [
"server1"
]
},
"values": [
[
1429950000000,
46,
3
],
[
1429960000000,
62,
3
],
[
1429970000000,
183,
3
],
[
1429980000000,
156,
3
],
[
1429990000000,
205,
3
]
]
}
],
"stats": {
"rawCount": 5
}
}
]
}
and I want to be able to only get the first two items of every value part of the item. Foe example I want to return [[1429950000000,46],[1429960000000,62],[1429970000000,183],.....] in a scope variable so I can eventually use it for a graph. I am new to angular and web dev in general but this is the way I've tried it so far.
$http({
url: 'file.json',
method: 'POST',
data: '(query data here)'
}).then(function(data, status){
$scope.solarData = data.tags.results.values;
conosle.log($scope.solarData);
});
You can use map:
var custom = data.tags[0].results[0].values.map(function(values) {
return [values[0], values[1]];
});
You can use slice if you want to return a lot of items or a variable number of them like
return values.slice(0, 2);
//---------------------^ replace this
var data = {
"tags": [{
"name": "SolarData",
"results": [{
"groups": [{
"name": "type",
"type": "number"
}],
"attributes": {
"customer": [
"Acme"
],
"host": [
"server1"
]
},
"values": [
[
1429950000000,
46,
3
],
[
1429960000000,
62,
3
],
[
1429970000000,
183,
3
],
[
1429980000000,
156,
3
],
[
1429990000000,
205,
3
]
]
}],
"stats": {
"rawCount": 5
}
}]
}
var custom = data.tags[0].results[0].values.map(function(values) {
return [values[0], values[1]];
});
console.log(custom);
var requirementArray = new Array();
for (i = 0; i < $scope.solarData.length ; i++) {
var pare = new Array();
pare.push($scope.solarData[i][0]);
pare.push($scope.solarData[i][1]);
requirementArray.push(pare);
}
requirementArray will be :
[[1429950000000,46],[1429960000000,62],[1429970000000,183],.....]
You can use Array.map for that:
$http({
url: 'file.json',
method: 'POST',
data: '(query data here)'
}).then(function(data, status){
$scope.solarData = data.tags[0].results[0].values.map(
function(curVal, index, arr) {
return [curVal[0], curVal[1]];
}
);
conosle.log($scope.solarData);
});

Categories

Resources