Data Table : Table has no columns - json

I am getting Table has no columns.× issue and i am not able to figure out why... Can you please help me understand whats wrong?
My HTML:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: "<JSON URL>",
dataType: "json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
JAVA CODE:
I am using code similar to one presented in the example
https://github.com/google/google-visualization-java/blob/master/examples/src/java/SimpleExampleServlet.java
MY JSON :
{
"rows":[
{
"cells":[
{
"value":{"value":"A","objectToFormat":"A","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
},
{
"value":{"value":"1","objectToFormat":"1","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
}
],
"customProperties":{}
},
{
"cells":[
{
"value":{"value":"B","objectToFormat":"B","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
},
{
"value":{"value":"0","objectToFormat":"0","null":false,"type":"TEXT"},
"formattedValue":null,
"customProperties":{},
"null":false,
"type":"TEXT"
}
],
"customProperties":{}
}
],
"customProperties":{},
"warnings":[],
"localeForUserMessages":null,
"numberOfRows":2,
"numberOfColumns":2,
"columnDescriptions":[
{"id":"Option","type":"TEXT","label":"Option","pattern":"","customProperties":{}},
{"id":"Count","type":"TEXT","label":"Count","pattern":"","customProperties":{}}
]
}

As were noted, google.visualization.DataTable expects JSON data to be provided in the format that is different from the one specified in question. Basically there are two options available:
modify Java servlet to generate JSON in format supported by google.visualization.DataTable
convert the generated JSON data
Below is demonstrated how to convert the provided JSON data to be compatible with google.visualization.DataTable(second option)
// Load the Visualization API and the piechart package.
google.load('visualization', '1', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
/*var jsonData = $.ajax({
url: "<JSON URL>",
dataType: "json",
async: false
}).responseText;*/
var jsonData = {
"rows": [
{
"cells": [
{
"value": { "value": "A", "objectToFormat": "A", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
},
{
"value": { "value": "1", "objectToFormat": "1", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
}
],
"customProperties": {}
},
{
"cells": [
{
"value": { "value": "B", "objectToFormat": "B", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
},
{
"value": { "value": "0", "objectToFormat": "0", "null": false, "type": "TEXT" },
"formattedValue": null,
"customProperties": {},
"null": false,
"type": "TEXT"
}
],
"customProperties": {}
}
],
"customProperties": {},
"warnings": [],
"localeForUserMessages": null,
"numberOfRows": 2,
"numberOfColumns": 2,
"columnDescriptions": [
{ "id": "Option", "type": "TEXT", "label": "Option", "pattern": "", "customProperties": {} },
{ "id": "Count", "type": "TEXT", "label": "Count", "pattern": "", "customProperties": {} }
]
};
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(convertToDataTableJson(jsonData));
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, { width: 400, height: 240 });
}
function convertToDataTableJson(json)
{
var outJson = { cols: [], rows: []};
json.columnDescriptions.forEach(function(c){
outJson.cols.push({ "id": c.id, "label": c.label, "pattern": c.pattern, "type": c.type == "TEXT" ? "string" : "number" });
});
json.rows.forEach(function(r){
var cells = {c : []};
r.cells.forEach(function(c){
cells.c.push({ "v": c.value.value, "f": null });
});
outJson.rows.push(cells);
});
return outJson;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<div id="chart_div"></div>

Related

How to search JSON key that contains specific string with jq?

I have a JSON data:
{
"orderTotal_1": {
"fields": {
"button": {
"actionDialog": null,
"actionUrl": null,
"clicked": false,
"enable": true,
"text": "LANJUTKAN KE PEMBAYARAN",
"textColor": null
},
"payment": {
"pay": "Rp1.953.800",
"taxTip": "Termasuk PPN, jika berlaku.",
"title": "Total"
},
"timestamp": 1522355946093
},
"id": "1",
"tag": "orderTotal",
"type": "biz"
},
"rightContainer_10010": {
"fields": {
"css": {
"backgroundColor": null,
"floatPosition": "right",
"marginTop": null,
"width": "388px"
}
},
"id": "10010",
"tag": "rightContainer",
"type": "container"
},
"toPayBtn_10021": {
"fields": {
"clicked": false,
"enable": true,
"text": "LANJUTKAN KE PEMBAYARAN"
},
"id": "10021",
"tag": "toPayBtn",
"type": "biz"
},
"voucherInput_1": {
"fields": {
"buttonText": "GUNAKAN",
"placeHolder": "Masukkan Kode Voucher",
"status": "default"
},
"id": "1",
"tag": "voucherInput",
"type": "biz"
}
}
I want to get toPayBtn_10021 but the number 10021 is dynamic. So it can be toPayBtn_34 toPayBtn_21 etc.
This is the output that I want to achieve:
"toPayBtn_10021": {
"fields": {
"clicked": false,
"enable": true,
"text": "LANJUTKAN KE PEMBAYARAN"
},
"id": "10021",
"tag": "toPayBtn",
"type": "biz"
}
This is what I have tried:
jq '.toPayBtn*'
But it results in:
jq: error: syntax error, unexpected $end (Unix shell quoting issues?) at <top-level>, line 1:
.toPayBtn*
jq: 1 compile error
exit status 3
Regex doesn't seem to work with jq How do I fix it ?
with_entries( select(.key | test("^toPayBtn_")) )
produces the output you want. You might want to tweak the regex.
This is angular filter example search text in search box it will only show object which have a search key.
<html ng-app="app">
<head>
<title>App</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<style>
th {
display: table-cell;
vertical-align: inherit;
font-weight: bold;
text-align: center;
}
</style>
</head>
<body>
<div ng-controller="ctrl">
<input type="text" ng-model="search" placeholder="Search">
{{search}}
<table class="table table-bordered">
<thead>
<tr>
<th>OBJECT</th>
</tr>
</thead>
<h4>{{displayById}}</h4>
<tbody>
<tr ng-repeat="x in jsonData | filter: search">
<td>{{x}}</td>
</tr>
</tbody>
</table>
</div>
<script>
var ngmodule = angular.module("app", []);
ngmodule.controller("ctrl", ["$scope", "$log","$timeout",
function ($scope, $log, $timeout) {
$scope.init = function(){
console.log("$timeout")
}
$timeout($scope.init);
$scope.jsonData = [{
"orderTotal_1": {
"fields": {
"button": {
"actionDialog": null,
"actionUrl": null,
"clicked": false,
"enable": true,
"text": "LANJUTKAN KE PEMBAYARAN",
"textColor": null
},
"payment": {
"pay": "Rp1.953.800",
"taxTip": "Termasuk PPN, jika berlaku.",
"title": "Total"
},
"timestamp": 1522355946093
},
"id": "1",
"tag": "orderTotal",
"type": "biz"
},
"rightContainer_10010": {
"fields": {
"css": {
"backgroundColor": null,
"floatPosition": "right",
"marginTop": null,
"width": "388px"
}
},
"id": "10010",
"tag": "rightContainer",
"type": "container"
},
"toPayBtn_10021": {
"fields": {
"clicked": false,
"enable": true,
"text": "LANJUTKAN KE PEMBAYARAN"
},
"id": "10021",
"tag": "toPayBtn",
"type": "biz"
},
"voucherInput_1": {
"fields": {
"buttonText": "GUNAKAN",
"placeHolder": "Masukkan Kode Voucher",
"status": "default"
},
"id": "1",
"tag": "voucherInput",
"type": "biz"
}
}];
}]);
</script>
</body>
</html>

Ethereum / Solidity getting smartcontract events in the geth console

So I tried to retrieve the events generated by my smartcontract
var abi = [{
"constant": false,
"inputs": [{
"name": "_value",
"type": "int32"
}],
"name": "changeLowerTrigger",
"outputs": [],
"payable": false,
"type": "function"
}, {
"constant": true,
"inputs": [],
"name": "metric",
"outputs": [{
"name": "name",
"type": "string",
"value": "place_holder_metric_name_to_be_autogenerated"
}, {
"name": "value",
"type": "int32",
"value": "7"
}],
"payable": false,
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_value",
"type": "int32"
}],
"name": "changeUpperTrigger",
"outputs": [],
"payable": false,
"type": "function"
}, {
"constant": false,
"inputs": [{
"name": "_value",
"type": "int32"
}],
"name": "update",
"outputs": [],
"payable": false,
"type": "function"
}, {
"anonymous": false,
"inputs": [{
"indexed": false,
"name": "_value",
"type": "int32"
}],
"name": "ValueChanged",
"type": "event"
}, {
"anonymous": false,
"inputs": [{
"indexed": false,
"name": "_alarm",
"type": "string"
}, {
"indexed": false,
"name": "_value",
"type": "int32"
}],
"name": "Alarm",
"type": "event"
}]
var MyContract = web3.eth.contract(abi);
var myContractInstance = MyContract.at(
'0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9');
var events = myContractInstance.allEvents();
// watch for changes
events.watch(function(error, event) {
if (!error)
console.log(event);
});
// Or pass a callback to start watching immediately
var events = myContractInstance.allEvents(function(error, log) {
console.log(err, log);
});
But it returns only:
> events
{
callbacks: [function(error, log)],
filterId: "0xd6af6f5a7273fe21452f00c4682456",
getLogsCallbacks: [],
implementation: {
getLogs: function(),
newFilter: function(),
poll: function(),
uninstallFilter: function()
},
options: {
address: "0x3B03c46Dfc878FeF9fAe8de4E32a6718f2E250e9",
from: undefined,
fromBlock: undefined,
to: undefined,
toBlock: undefined,
topics: []
},
pollFilters: [],
requestManager: {
polls: {
0xd6af6f5a7273fe21452f00c4682456: {
data: {...},
id: "0xd6af6f5a7273fe21452f00c4682456",
callback: function(error, messages),
uninstall: function()
}
},
provider: {
newAccount: function(),
send: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),
sendAsync: function github.com/ethereum/go-ethereum/console.(*bridge).Send-fm(),
sign: function(),
unlockAccount: function()
},
timeout: {},
poll: function(),
reset: function(keepIsSyncing),
send: function(data),
sendAsync: function(data, callback),
sendBatch: function(data, callback),
setProvider: function(p),
startPolling: function(data, pollId, callback, uninstall),
stopPolling: function(pollId)
},
formatter: function(),
get: function(callback),
stopWatching: function(callback),
watch: function(callback)
}
But what I want, is the events shown in the next image at the very bottom(e.g.Value Changed value:7):
Since the events are displayed in the ETH-Wallet there should be a way. I rly just want a way to get the latest events in the geth console (or sth similare).
Thanks for any help I'm kinda lost and having some of the worst googling of my life.
All you need to do is to call get() on the result object you've got and posted in your answer. Its described in official documentation and can be found here

Returning metadata value from JSON API Response

I have an api request that returns JSON data which is then used to populate an html table. I am able to populate the table with item.name ... I would like to add the metadata value for player.field but I have not been able to access it. Here is the JSON response:
{
"list": [
{
"id": 55,
"name": "0046GS (RMS03241708)",
"description": "S 12-7 M-S 10-9",
"uuid": "6f4b5bfd-6d17-4095-9e48-7b9313f7f8c6",
"previewPlayer": false,
"enabled": true,
"mac": "00-00-00-00-00-00",
"type": "CHROMEBOX",
"distributionServer": {
"id": 2,
"name": "Main",
"driver": "IP_P2P"
},
"playergroups": [
{
"id": 2,
"name": "GameStop",
"numberOfPlayers": 454
}
],
"playerDisplays": [
{
"id": 55,
"name": "Display 1",
"channel": {
"id": 53,
"name": "GameStop TV"
},
"screenCounter": 1
}
],
"requestLogs": false,
"downloadThreads": 1,
"unusedFilesCache": 24,
"planDeliveryMethod": "CONTENT_MANAGER_DIRECT",
"pollingInterval": 1,
"pollingUnit": "MINUTES",
"logLevel": "normal",
"metadataValue": [
{
"id": 12512,
"value": "true",
"playerMetadata": {
"id": 34,
"name": "Player.field",
"datatype": "BOOLEAN",
"valueType": "ANY",
"order": 4
}
},
{
"id": 1085,
"value": "77056",
"playerMetadata": {
"id": 31,
"name": "Player.ZipCode",
"datatype": "STRING",
"valueType": "ANY",
"order": 30
}
},
{
"id": 1071,
"value": "22:15",
"playerMetadata": {
"id": 10,
"name": "Player.ScreenOff_Wednesday",
"datatype": "STRING",
"valueType": "ANY",
"order": 12
}
}
],
"usedPairingKey": "HBVULW",
"active": "ACTIVE",
"lastModified": "2017-04-03 20:12:43",
"timezoneOffset": "0"
}
],
"offset": 0,
"count": 68
}
Here is the ajax request:
$.ajax({
type: 'GET',
url: "https://sampleserver.com:8080/ContentManager/api/rest/players?limit=1&offset=0&sort=name&filters=%7BplayerStatus%20:%20%7Bvalues:%5B'ACTIVE'%5D,%20comparator%20:%20'eq'%7D%7D",
dataType: "json",
success: function(data) {
$.each(data.list, function(i, item) {
var tr = $('<tr><td>'+item.name+'</td><td>'+some.JSONResponse+'</td></tr>').appendTo('#scalaapi');
});
}
});
I am stuck on how to specifically display the value for player.field ... "value": "true",
It feels like it should be simple, but my attempts have all been met with undefined.
Attempted if statement...
success: function(data) {
$.each(data.list, function(i, item) {
var tr = $('<tr><td>'+item.name+'</td><td class="val">...</td></tr>').appendTo('#scalaapi');
var bool = function(i,item) {if (item.metadataValue.id = '12512');
tr.find('.val').text(bool);};
});
}
});

jQuery Each Multidimensional JSON Array

I have the following problem which I can't solve for trying for 3 days now. I have an JSON array:
var geojson = {
type: 'FeatureCollection',
features: [
{
"type": "Feature",
"geometry": {
"coordinates": [
5.140439,
51.686608
],
"type": "Point"
},
"properties": {
"title": "TEST1",
"rentals": true,
"tackleshop": false,
"fuel": false,
"marker-color": "#1087bf",
"marker-size": "large",
"marker-symbol": "harbor"
}
},
{
"type": "Feature",
"geometry": {
"coordinates": [
5.134060,
51.686890
],
"type": "Point"
},
"properties": {
"title": "TEST2",
"rentals": true,
"tackleshop": false,
"fuel": true,
"marker-color": "#1087bf",
"marker-size": "large",
"marker-symbol": "harbor"
}
},
{
"type": "Feature",
"geometry": {
"coordinates": [
5.133729,
51.681425
],
"type": "Point"
},
"properties": {
"title": "TEST3",
"rentals": false,
"tackleshop": true,
"fuel": true,
"marker-color": "#1087bf",
"marker-size": "large",
"marker-symbol": "harbor"
}
}
]
};
What I have been tested now:
$.each(geojson, function() {
$.each(this, function(key, value) {
$.each(this, function(value, featuress) {
console.log(featuress.properties.title);
});
});
});
The result I want:
I want a $.each which goes through this json array where I am able to display the variable for as example: "title" for each feature.
Who can help me out? Cheers!
You looped over a JSON object for 2 times, I removed the outer foreach loops. You can only iterate over a list - features in this case. See the snippet:
var geojson = {
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"geometry":{
"coordinates":[
5.140439,
51.686608
],
"type":"Point"
},
"properties":{
"title":"TEST1",
"rentals":true,
"tackleshop":false,
"fuel":false,
"marker-color":"#1087bf",
"marker-size":"large",
"marker-symbol":"harbor"
}
}
]
}
$.each(geojson.features, function(i, feature) {
console.log(feature.properties.title);
});
You looped over an object
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For further reading:
Beginner JavaScript: Working with JSON and Objects in JavaScript
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
As your code, geojson is a json object, it's not a json array.
Example for a json array is [{"name":"item 1"},{"name": "item2} ].
To go throught list features and display its property, you could
try this:
$.each(geojson.features, function(index, feature) {
console.log(feature.properties.title);
});

filter or find using lodash to find an object then use the nested array

I have the following json
{
"records": [
{},
{},
{},
{},
{},
{},
{},
{},
{
"id": "recoEidAQO7qiu7M9",
"fields": {
"Room": "Exterior",
"img": [
{
"id": "attVi68pAaCpX1fDQ",
"url": "https://dl.airtable.com/7munMtXcSK6WHDtMFEqA_IMG_0877%20New%20paint%20(1024x768).jpg",
"filename": "IMG_0877 New paint (1024x768).jpg",
"size": 566394,
"type": "image/jpeg",
"thumbnails": {
"small": {
"url": "https://dl.airtable.com/uFr8bJcSqyPFoe6n91EA_small_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 48,
"height": 36
},
"large": {
"url": "https://dl.airtable.com/zfgQJqL7Si2Vi9kZe3Bx_large_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 512,
"height": 512
}
}
}
]
},
"createdTime": "2016-08-16T21:29:37.000Z"
}
]
}
I'm attempting to use lodash. I'm trying get the url for the value 'Exterior' so that with jquery I can concatenate and build the following
$('wrapper').css('background-image' , 'url('+url+')')
Thanks in advance
You can use a combination of find and get in order to get the url:
var obj = _.find(json.records, function(el) {
return _.get(el, 'fields.Room') === 'Exterior';
});
var url = _.get(obj, 'fields.img[0].url');
var json = {
"records": [
{},
{},
{},
{},
{},
{},
{},
{},
{
"id": "recoEidAQO7qiu7M9",
"fields": {
"Room": "Exterior",
"img": [
{
"id": "attVi68pAaCpX1fDQ",
"url": "https://dl.airtable.com/7munMtXcSK6WHDtMFEqA_IMG_0877%20New%20paint%20(1024x768).jpg",
"filename": "IMG_0877 New paint (1024x768).jpg",
"size": 566394,
"type": "image/jpeg",
"thumbnails": {
"small": {
"url": "https://dl.airtable.com/uFr8bJcSqyPFoe6n91EA_small_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 48,
"height": 36
},
"large": {
"url": "https://dl.airtable.com/zfgQJqL7Si2Vi9kZe3Bx_large_IMG_0877%20New%20paint%20(1024x768).jpg",
"width": 512,
"height": 512
}
}
}
]
},
"createdTime": "2016-08-16T21:29:37.000Z"
}
]
};
var obj = _.find(json.records, function(el) {
return _.get(el, 'fields.Room') === 'Exterior';
});
var url = _.get(obj, 'fields.img[0].url');
console.log(url);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>