How to transform complex json structure using Groovy? - json

first of all, thanks for your time!
So i've been using Groovy for a couple of weeks now but i can't seems to be able to transform the following json structure:
{
"collection_1": [
[
"value_1",
"value_2",
"value_3"
],
[
"value_1",
"value_2",
"value_3",
"value_4"
]
],
"collection_2": [
[
"value_1",
"value_2",
"value_3",
"value_4",
"value_5"
]
],
"collection_3": [
[
"value_1",
"value_2"
]
]
}
To something like:
{
"collection_1": [
[
"value_1": false,
"value_2": false,
"value_3": false
],
[
"value_1": false,
"value_2": false,
...
Here is how i did it:
Map<String, Object> getSelectableItems(Map<String, Object> jsonDeserialized) {
def selectableItems = [:]
jsonDeserialized.each { collection, subCollection ->
selectableItems.put(collection, [:])
subCollection.eachWithIndex { items, index ->
selectableItems.get(collection).putAt(index, items.collect { value ->
[
"${value}" : false
]
})
}
}
return selectableItems
}
​
I've been trying for days, it isn't that hard, i even succeed but the final code is looking terribly wrong.
Do you have any idea of how I could achieve something like so with the power of Groovy?
Thanks groovy pros :D

import groovy.json.*
def data = new JsonSlurper().parseText('''
{...your json here...}
''')
data.replaceAll { k, v -> v = v.collect { it.collectEntries { [it,false] } } }
println new JsonBuilder(data).toPrettyString()
output:
{
"collection_1": [
{
"value_1": false,
"value_2": false,
"value_3": false
},
{
"value_1": false,
"value_2": false,
"value_3": false,
"value_4": false
}
],
"collection_2": [
{
"value_1": false,
"value_2": false,
"value_3": false,
"value_4": false,
"value_5": false
}
],
"collection_3": [
{
"value_1": false,
"value_2": false
}
]
}

Related

How to write language syntax definition for Solr in Monarch (Monaco Editor)?

I have a Solr query like this one:
(content_language:English OR content_language:"American French") AND ("Los Angeles" OR Washington)
I am trying to at least have a autocomplete for the "content_language" string but I was not able to make it. Here is my definition for Monarch that I don't know what I am missing:
return {
defaultToken: 'invalid',
ignoreCase: true,
keywords: [
'content_language'
],
operators: [
'AND', 'OR'
],
tokenizer: {
root: [
{include: '#whitespace'},
{ include: '#strings' },
[
/[\w##$]+/, {
cases: {
'#keywords': {token: 'keyword'},
'#operators': 'operator',
}
}
]
],
whitespace: [[/\s+/, 'white']],
strings: [
[/'/, { token: 'string', next: '#string' }],
[/"/, { token: 'string.double', next: '#stringDouble' }]
],
string: [
[/[^']+/, 'string'],
[/''/, 'string'],
[/'/, { token: 'string', next: '#pop' }]
],
stringDouble: [
[/[^"]+/, 'string.double'],
[/""/, 'string.double'],
[/"/, { token: 'string.double', next: '#pop' }]
],
},
};

JSON only reading first element of array

I am working on a discord bot using Typescript, and I am having a problem reading from the config.JSON file.
This is the read vars function:
fs.readFile('config.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
config = JSON.parse(data);
console.log(config);
const store = config.configstore[0];
roster = config.roster[0];
}});
and this is the config.json file:
{
"configstore": [
{"prefix": "!!"},
{"wallTime": 5},
{"bufferTime": 15},
{"wall": "false"},
{"buffer": "false"},
{"lastWallTime": "-1"},
{"lastBufferTime": "-1"},
{"wallCheckRole": "Role"},
{"bubfferCheckRole": "Role"}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
When I print out the raw 'config' variable it prints this:
{
configstore: [
{ prefix: '!!' },
{ wallTime: 5 },
{ bufferTime: 15 },
{ wall: 'false' },
{ buffer: 'false' },
{ lastWallTime: '-1' },
{ lastBufferTime: '-1' },
{ wallCheckRole: 'Role' },
{ bubfferCheckRole: 'Role' }
],
roster: [ { discID: 'DiscordID', ign: 'IGN' } ]
}
But when I print the store variable it prints this:
{ prefix: '!!' }
The roster is normal as well.
The roles and ids are strings, but I changed it since I don't want them leaked.
These are some examples of what you are probably trying to achieve:
let config1 = {
"configstore": [
{"prefix": "!!"},
{"wallTime": 5},
{"bufferTime": 15},
{"wall": "false"},
{"buffer": "false"},
{"lastWallTime": "-1"},
{"lastBufferTime": "-1"},
{"wallCheckRole": "Role"},
{"bubfferCheckRole": "Role"}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
let config2 = {
"configstore": [
{
"prefix": "!!",
"wallTime": 5,
"bufferTime": 15,
"wall": "false",
"buffer": "false",
"lastWallTime": "-1",
"lastBufferTime": "-1",
"wallCheckRole": "Role",
"bubfferCheckRole": "Role"
}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
//prints {"prefix":"!!"}
console.log("configstore1:", JSON.stringify(config1.configstore[0]));
//prints {"discID":"discordID","ign":"IGN"}
console.log("roster1:", JSON.stringify(config1.roster[0]));
//prints {"prefix":"!!","wallTime":5,"bufferTime":15,"wall":"false","buffer":"false","lastWallTime":"-1","lastBufferTime":"-1","wallCheckRole":"Role","bubfferCheckRole":"Role"}
console.log("configstore2:", JSON.stringify(config2.configstore[0]));
//prints {"discID":"discordID","ign":"IGN"}
console.log("roster2:", JSON.stringify(config2.roster[0]));

How to export the api call results to a csv with the values of single response in one row?

My api response looks like below
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
Now in react, I want to export the results to a csv. I can do it by export-to-csv but the formatting is the issue here. I want the values of each question of a single response in one row under their labels(questions). So if I have two response like above I want to have export it in two rows, not 8 as there are 8 total questions.
Here is how I want it to get exported.
I have tried so far like this but no luck.
this is my export data function
exp =()=>{
const raw = []
console.log(this.state.data[0].sbm_id)
axios.get(`/dashboard/${this.props.proj_id}/whole_sub/`)
.then(res=>{
// console.log('1')
// console.log(res.data[0][0])
// console.log('2')
for (let i =0;i<this.state.data.length;i++){
for(let j = 0;j<res.data[0].length;j++){
// let sub=[]
//res.data[i][j].ID = this.state.data[i].sbm_id
raw.push(res.data[i][j])
}
}
}
)
let curr = this.state
curr.exp = raw
this.setState({exp:curr.exp})
}
Here is my export function
rawExport=()=>{
const csvExporter = new ExportToCsv(optionsExp);
csvExporter.generateCsv(this.state.exp);
}
First step is to flatten the initial nested array to get a homogeneously shaped array, then you keep on reducing it further.
const data = [
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
];
const flattenArray = (arr) => [].concat.apply([], arr);
// Flatten the initial array
const flattenedArray = flattenArray(data);
// Keep on reducing the flattened array into an object
var res = flattenedArray.reduce((acc, curr) => {
const [key, val] = flattenArray(Object.entries(curr));
if (!acc[key]) {
acc[key] = [].concat(val);
} else {
val.forEach(x => {
if (!acc[key].includes(x)) {
acc[key].push(x);
}
});
}
return acc;
}, {});
console.log(res);

KendoUI Grid Server Binding Example

I have successfully set up several KendoUI Grids, but I cannot get one using server-side paging to work.
I modified my rest service so I will return a total value (hard coded right now).
I also modified my javascript source. [see below].
Usually I just get a blank screen.
Would be very grateful for any assistance.
Script:
$(document).ready(function(){
// Setup Rest Service
var loc = ( location.href );
var url = loc.substring( 0, loc.lastIndexOf( "/" ) ) + "/xpRest.xsp/test/";
dataSource = new kendo.data.DataSource({
pageSize: 20,
serverPaging: true,
serverFiltering: true,
serverSorting: true, transport : {
read : {
url : url + "READ",
dataType : "json"
},
type : "READ"
},
schema : {
total: "total",
model : {
id : "unid",
fields : {
unid : {
type : "string",
nullable : false
},
tckNbr : {
type : "string",
editable : false
},
tckSts : {
type : "string",
editable : false
}
}
}
}
});
grid = $("#grid-databound-dataItem").kendoGrid({
dataSource : dataSource,
height: 550,
filterable: true,
sortable: true,
pageable: true,
columns : [
{field : "tckNbr", title : "Number", type: "string"},
{field : "tckSts", title : "Status", type: "string"}
]
}).data("kendoGrid");
});
JSON feed:
[
{
"total":100,
"data":
[
{
"tckNbr":"3031",
"tckSts":"1 Not Assigned",
"unid":"0014DA9095BF6D638625810700597A36",
"tckReqs":"Bryan S Schmiedeler",
"tckNts":
[
"Bryan DeBaun"
],
"tckBUs":
[
"NAP\/IFI"
],
"tckApps":"GTM",
"tckType":"Issue",
"tckPriority":"Medium"
},
{
"tckNbr":"3031",
"tckSts":"1 Not Assigned",
"unid":"00598976D88226D2862581070059AD25",
"tckReqs":"Bryan S Schmiedeler",
"tckNts":
[
"Bryan DeBaun"
],
"tckBUs":
[
"NAP\/IFI"
],
"tckApps":"GTM",
"tckType":"Issue",
"tckPriority":"Medium"
}
]
}
]
Correct your JSON feed, you need to return object not array:
{
"total": 10,
"data": []
}
After that say what is data and what is total in you schema:
schema : {
total: "total",
data: "data",
.
.
}
Note: if you mock data like in your case (total: 100, data -> size is 2) your paginatio will be created by total parameter not data itself. You will see 5 pages with same data (that is ok).

Sort a store data based on inner JSON field sencha

i have a json in the following format:
{
"collection": [
{
"id": 4,
"tickets": [
{
"price": 40,
},
{
"price": 50,
}
],
},
{
"id": 1,
"tickets": [
{
"price": 10,
},
{
"price": 15,
}
]
},
]
}
STORE:
Ext.define("myProject.store.ABCs", {
extend: "Ext.data.Store",
config: {
model: "myProject.model.ABC",
autoLoad: false,
proxy: {
type: "ajax",
url: '', //myURL
reader: {
type: "json",
rootProperty: "collection", // this is the first collection
},
},
}
});
For this particular JSON i created the models as:
Ext.define("myProject.model.ABC", {
extend: "Ext.data.Model",
config: {
idProperty: "id",
fields:[
{name: "id", type: "int" },
],
hasMany: [
{
model: "myProject.model.XYZ",
name: "tickets",
associationKey: "tickets",
},
],
}
});
And second model as:
Ext.define("myProject.model.XYZ", {
extend: "Ext.data.Model",
config: {
// idProperty: "id",
fields:[
{name: "inner_id", type: "int" },
],
belongsTo: 'myProject.model.ABC'
}
});
This particular code creates a store and populates the models correctly.
var store = Ext.getStore('ABCs');
Now i want to sort this store based on store.tickets().getAt(0).get('price') that is sort the ABC records based on XYZ's first price property.
In the above json. ABC Records will be: [{id:4}, {id:1}]
But since first price in XYZ (40 > 10), i want to sort them and create [{id:1}, {id:4}]
Take a look at the Ext.util.Sorter class, where you can set a sorterFn. See the example at the top of the page - you should be able to simply write the logic for sorting records the way you describe.