putting selected values from the JSON - json

If I do the following on a query :
<cfdump var="#serializeJSON(findglobal)#">
I get the following:
{
"COLUMNS": [
"DELIVERED_PERCENTAGE",
"UNIQUE_PERCENTAGE",
"SPAM_PERCENTAGE",
"DROP_PERCENTAGE",
"REQUEST_PERCENTAGE",
"BOUNCE_PERCENTAGE",
"DEFERRED_PERCENTAGE",
"PROCESSED_PERCENTAGE",
"OPEN_PERCENTAGE",
"BLOCKED_PERCENTAGE"
],
"DATA": [
[
19.54,
6.06,
6.05,
0.63,
21.17,
0.85,
14.83,
20.53,
10.26,
0.19
]
]
}
But I am using Geikoboard which understand only the following format of JSON.
So I would like to have DELIVERED_PERCENTAGE, UNIQUE_PERCENTAGE for the label field below and all the values, like
19.54,6.06 etc for the value field below.
{
"item": [
{
"value": "11234",
"label": "Webmail",
"colour": "FFFF10AA"
},
{
"value": "10736",
"label": "Phone",
"colour": "FFAA0AAA"
},
{
"value": "230",
"label": "Webmail",
"colour": "FF5505AA"
},
{
"value": "280",
"label": "Webmail",
"colour": "FF0000AA"
}
]
}
Do I have to manually generate JSON ?

I think this is what you are looking for. Got it from some site; either Raymon Camden's or Ben Nadel's.
public array function queryToArray( required query qry ) {
var columns = arguments.qry.getColumnNames();
var OutputResult = [];
for( var i = 1; i LTE qry.recordCount; i++ ) {
var obj = {};
for( var k = 1; k LTE arrayLen( columns ); k++ ) {
structInsert( obj, columns[ k ], arguments.qry[ columns[ k ] ][ i ] );
}
arrayAppend(OutputResult, obj );
}
return OutputResult;
}
You would need to do something like this:
<cfset myJSON = queryToArray( myquery ) />
<cfoutput>#serializeJSON( myJSON )#</cfoutput>

Related

Google Sheet: How to define the "cols.label" value in JSON export?

I use a google sheet as an endpoint to import data into an html table. Depending on the type of data in the sheet I get a different JSON structure.
To explain the problem, I built a Google sheet with two very simple tables.
The only difference between the two tables is the Age field which is numeric in Sheet1 and textual in Sheet2.
Link document
If I use sheets as JSON endpont I get this behavior: Sheet1 exports the header correctly, but Sheet2 shows an empty header (column headers become normal row values).
Sheet1 JSON
{
"version": "0.6",
"reqId": "0",
"status": "ok",
"sig": "325167901",
"table": {
"cols": [
{
"id": "A",
"label": "Name",
"type": "string"
},
{
"id": "B",
"label": "Age",
"type": "number",
"pattern": "General"
}
],
"rows": [
{
"c": [
{
"v": "Vittorio"
},
{
"v": 52.0,
"f": "52"
}
]
}
],
"parsedNumHeaders": 1
}
}
Sheet2 JSON
{
"version": "0.6",
"reqId": "0",
"status": "ok",
"sig": "1566616543",
"table": {
"cols": [
{
"id": "A",
"label": "",
"type": "string"
},
{
"id": "B",
"label": "",
"type": "string"
}
],
"rows": [
{
"c": [
{
"v": "Name"
},
{
"v": "Age"
}
]
},
{
"c": [
{
"v": "Vittorio"
},
{
"v": "52"
}
]
}
],
"parsedNumHeaders": 0
}
}
Is there any way to fix Sheet2 behavior?
It seems there is a problem, meanwhile what I suggest is to test the JSON endpont labels as follows
const jsonString = `/*O_o*/
google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"1566616543","table":{"cols":[{"id":"A","label":"","type":"string"},{"id":"B","label":"","type":"string"}],"rows":[{"c":[{"v":"Name"},{"v":"Age"}]},{"c":[{"v":"Vittorio"},{"v":"52"}]}],"parsedNumHeaders":0}});`
function jsonWithLabels(jsonString) {
var json = JSON.parse(jsonString.slice(47,-2))
var labels = json.table.cols.map(c => c.label)
return (labels.join('') != '')
}
function test(){
console.log (jsonWithLabels(jsonString))
}
if false, you need to fetch the labels from row 1
const jsonString = `/*O_o*/
google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"1566616543","table":{"cols":[{"id":"A","label":"","type":"string"},{"id":"B","label":"","type":"string"}],"rows":[{"c":[{"v":"Name"},{"v":"Age"}]},{"c":[{"v":"Vittorio"},{"v":"52"}]}],"parsedNumHeaders":0}});`
var json = JSON.parse(jsonString.slice(47,-2))
var labels = json.table.cols.map(c => c.label)
console.log (labels.join('') != '')
here is a complete script to rebuild the table with and without labels
const jsonString = `/*O_o*/
google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"1566616543","table":{"cols":[{"id":"A","label":"","type":"string"},{"id":"B","label":"","type":"string"}],"rows":[{"c":[{"v":"Name"},{"v":"Age"}]},{"c":[{"v":"Vittorio"},{"v":"52"}]}],"parsedNumHeaders":0}});`
document.getElementById("json").innerHTML = myItems(jsonString.slice(47, -2))
function myItems(jsonString) {
var json = JSON.parse(jsonString);
var table = '<table>';
var flag = jsonWithLabels(json);
if (flag) {
table += '<tr>';
json.table.cols.forEach(colonne => table += '<th>' + colonne.label + '</th>')
table += '</tr>';
}
json.table.rows.forEach((row, index) => {
table += '<tr>';
row.c.forEach(cel => {
try { var valeur = cel.f ? cel.f : cel.v }
catch (e) { var valeur = '' }
if (!flag && index == 0) { table += '<th>' + valeur + '</th>' }
else { table += '<td>' + valeur + '</td>' }
})
table += '</tr>';
})
table += '</table>';
return table
}
function jsonWithLabels(json) {
var labels = json.table.cols.map(c => c.label);
return (labels.join('') != '')
}
table {border-collapse: collapse;}
th,td {border: 1px solid black;}
<div id="json">json here</div>

Use and Convert Array into JSON

I have this array
["123", "456", "789", "0"]
And I would like to build a JSON out of its values.
Expected result is
{
"list": [
{
"code": 123
},
{
"code": 456
},
{
"code": 789
},
{
"code": 0
}
]
}
How do I work this structure in javascript? Thank u for the help
You will have to create a loop and a JS variable that writes it that way then JSON.Stringify it out once complete.... I.e.
var json = { list: [] };
for(i = 0 ; i < arr.length ; i++) {
json.list.push( { code : arr[i] } );
}
var stringOutput = JSON.Stringify(json)
Note: not tried to compile or run the code but that should be close to what you want.
As a one-liner you can do the following:
let result = {"list": ["123", "456", "789", "0"].map((code) => { return {"code":code} })};
Or to break out the steps and to use older syntax:
var orig = ["123", "456", "789", "0"];
var list = orig.map(function(code) {
return {"code": code};
});
var result = {"list": list};

underscore.js how to get an element from a JSON object using _.filter

I have the following JSOn object ( Array of elements )
var roles = [
{
"label": "alpha",
"children": [
{"label": "role1","title": "role1","value": "1"},
{"label": "role2","title": "role2","value": "2"}
]
},
{
"label": "beta",
"children": [
{"label": "role3","title": "role3","value": "3"},
{"label": "role4","title": "role4","value": "4"}
]
},
{
"label": "delta",
"children": [
{"label": "role5","title": "role5","value": "5"},
{"label": "role6","title": "role6","value": "6"}
]
}
]
I am trying to get ( and later remove.. ) an element with a specific label
I defined a where object
var where = {key: 'label', value:"alpha"};
and I filter the object :
var filteredRoles = _.filter(roles, function (el) {
return el[where.key] && _.isArray(el[where.key]) &&
_.indexOf(el[where.key], where.value) >= 0;
});
console.log("found "+JSON.stringify(filteredRoles, null, 2));
but I cannot get it : found = []
where am I wrong ?
thanks for feedback
try this
var result = _.filter(roles, function(role) {
return (role[where.key] === where.value) && _.isArray(role['children']);
})
here is a working plunk

how to convert json tree to table, and back(same table to json tree)

i need to convert json tree to table, and back(same table to json tree), PostgreSQL
example:
{
"id": 1,
"title": "Example Node(UnDeleteable, and no counted)",
"items": [
{
"id": 2,
"title": "dfsdfs",
"items": [
{
"id": 3,
"title": "dfsfddfsfd",
"items": [
{
"id": 4,
"title": "dsffdsdfsfdsdfs",
"items": [
{
"id": 5,
"title": "dfsdsfdfsddfs",
"items": []
}
]
}
]
}
]
}
]
}
]
need to be:
ParentId ChildId title
NULL 1 "Example Node(UnDeleteable, and no counted)"
1 2 "dfsdfs"
2 3 "dfsfddfsfd"
etc
....
...
...
someone can help me with that? Thanks!
I think all you need is a two-dimensional array and recursion.
here is my code about tanslating a json to a tree. I think it is easy to feed your needs with a little modification.
var jsonTreeServ = {};
jsonTreeServ.toTreeJson = function (jsonObj, treeArr) {
for (var k in jsonObj) {
var val = jsonObj[k];
if (val instanceof Object) {
var node = {};
node.title = k;
node.value = '';
node.visible = true;
node.nodes = [];
treeArr.push(node);
jsonTreeServ.toTreeJson(val, node.nodes);
} else {
var node = {};
node.title = k;
if(null!==val && ''!==val){
node.title += '=';
val = jsonTreeServ.translateTimestamp(node.title, val);
}
node.value = val;
node.visible = true;
treeArr.push(node);
}
}
return treeArr;
}

How to convert JSON Array in JSON Object

I have a JSON Array in below format which I want to convert to JSON Object in (key,value) pair.
Since I am new to JSON I don't know how to achieve this.
{
"id": [
"100",
"101",
"102"
],
"Name": [
"ajit",
"amol",
"kiran"
],
"sex": [
"Male",
"Male",
"Male"
]
}
I want to convert above in the format like
[
{
"id": "100",
"Name": "ajit",
"Sex": "Male"
},
{
"id": "101",
"Name": "amol",
"Sex": "Male"
},
{
"id": "102",
"Name": "kiran",
"Sex": "Male"
}
]
Can you guys share your valuable thoughts on how to do this please?
Ajit
Assuming lots of things this works for the example,
var arrayOfObjects = [] ;
/**
* #params Object obj formated like the first one
*/
var i = 0,
arrayOfObjects = [] ;
for( prop in obj ) {
if ( prop instanceof Array ) {
for( i = 0 ; i < obj[prop].length ; ++i ) {
if ( typeof arrayOfObjects[i] !== undefined ) {
arrayOfObjects[i][prop] = obj[prop][i] ;
} else {
var newObj = {} ;
newObj[prop] = obj[prop][i] ;
arrayOfObjects.push(newObj) ;
}
}
}
}