I have this JSON string
[
{
uri : '/someuri/one',
title : 'Title 1',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-1'
},
{
uri : '/someuri/two',
title : 'Title 2',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-2'
},
{
uri : '/someuri/three',
title : 'Title 3',
displayLocation : 'ACTION_MENU',
masterData : 'JOB',
iconClass : 'icon-class-3'
},
{
uri : '/someuri/four',
title : 'Title 4',
displayLocation : 'SUMMARY',
masterData : 'LOCATION',
iconClass : 'icon-class-4'
}
]
I am converting it to
[
{
iconClass : 'icon-class-1',
id : 'anythingUnique',
text : 'Title 1'
},
{
iconClass : 'icon-class-2',
id : 'anythingUnique',
text : 'Title 2'
}
]
using following code
function myCustomFilter(inputJSONStr) {
return _.each(inputJSONStr.filter(function(action){
return action.masterData === 'LOCATION' && action.displayLocation === 'ACTION_MENU';
}), function (action) {
return [{iconClass: action.iconClass, id: 'anythingUnique', text: action.title}];
});
But its returning me JSON string
[
{
uri : '/someuri/one',
title : 'Title 1',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-1'
},
{
uri : '/someuri/two',
title : 'Title 2',
displayLocation : 'ACTION_MENU',
masterData : 'LOCATION',
iconClass : 'icon-class-2'
}
]
Can anyone suggest what I am doing wrong?
You could use map to do this:
_(inputJSONStr).filter({masterData: 'LOCATION', displayLocation: 'ACTION_MENU'})
.map(function(a) {
return {iconClass: a.iconClass, id: 'anythingUnique', text: a.title};
}).value();
I've changed your filter a little, but you could do it your way if you wanted, and I've used a functional approach with chaining, but you could do it imperatively if that makes you more comfortable. Map effectively replaces an array element with the returned element.
Related
This function creates a playlist using the Spotify API. Which returns a body containing an 'id' that I need.
function createPlaylist(pc) {
let index = partyCodeExists(pc)
let at = token_arr[index]
let userID = user_ids[index]
var authOptions = {
url: 'https://api.spotify.com/v1/users/' + userID + '/playlists',
body: JSON.stringify({
'name': pc,
'description': 'Jukibox playlist',
'public': false
}),
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + at,
'Content-Type': 'application/json'
}
};
request.post(authOptions, function (error, response, body) {
console.log(body);
console.log(body.id);
});
};
The lower console logs give the following output:
{
"collaborative" : false,
"description" : null,
"external_urls" : {
"spotify" : "https://open.spotify.com/user/larsonadam-us/playlist/5pZ3C6ZRB3C9Tv9Z3EdA0g"
},
"followers" : {
"href" : null,
"total" : 0
},
"href" : "https://api.spotify.com/v1/users/larsonadam-us/playlists/5pZ3C6ZRB3C9Tv9Z3EdA0g",
"id" : "5pZ3C6ZRB3C9Tv9Z3EdA0g",
"images" : [ ],
"name" : null,
"owner" : {
"display_name" : null,
"external_urls" : {
"spotify" : "https://open.spotify.com/user/larsonadam-us"
},
"href" : "https://api.spotify.com/v1/users/larsonadam-us",
"id" : "larsonadam-us",
"type" : "user",
"uri" : "spotify:user:larsonadam-us"
},
"primary_color" : null,
"public" : true,
"snapshot_id" : "90UhGQhCi0Xq2vch8g/wrQ5BZoKK5cmIkiwybqJLUIsEAljI+L90YPzpD59T8zwP",
"tracks" : {
"href" : "https://api.spotify.com/v1/users/larsonadam-us/playlists/5pZ3C6ZRB3C9Tv9Z3EdA0g/tracks",
"items" : [ ],
"limit" : 100,
"next" : null,
"offset" : 0,
"previous" : null,
"total" : 0
},
"type" : "playlist",
"uri" : "spotify:user:larsonadam-us:playlist:5pZ3C6ZRB3C9Tv9Z3EdA0g"
}
undefined
Why does the second option display undefined?
Another note, I have body parser and it works in other areas of the code
The problem is that the return is a string. You need to handle the return before you get the ID. Try this.
console.log(body)
let bodyObject = JSON.parse(body)
console.log(bodyObject.id)
Here is my datagrid part in jsp:
<title>Device</title>
<script type="text/javascript">
var dataGrid;
$(function() {
dataGrid = $('#dataGrid').datagrid({
url : '${ctx}' + '/drivers/dataGrids',
striped : true,
rownumbers : true,
pagination : true,
singleSelect : true,
idField : 'id',
sortName : 'driversstatus',
sortOrder : 'desc',
pageSize : 15,
pageList : [ 10, 20, 30, 40, 50, 100, 200, 300, 400, 500 ],
frozenColumns : [ [ {
width : '100',
title : 'id',
field : 'id',
sortable : true
}, {
width : '80',
title : 'Device Name',
field : 'driversname',
sortable : true
} , {
width : '80',
title : 'Device ip',
field : 'driversip',
sortable : true
}, {
width : '80',
title : 'Device type',
field : 'driverstype',
sortable : true,
}, {
width : '80',
title : 'Device Status',
field : 'driversstatus',
sortable : true,
formatter : function(value, row, index) {
switch (value) {
case 0:
return 'Online';
case 1:
return 'Offline';
}
}
} ,{
width : '80',
title : 'Add Time',
field : 'addtime',
sortable : true,
}
] ],
toolbar : '#toolbar'
});
});
And here is my datagrid code in controller class:
#RequestMapping("/dataGrids")
#ResponseBody
public Grid jsonList(Drivers eqimInfo, PageFilter ph) {
Grid grid = new Grid();
grid.setPage(ph.getPage());
grid.setRows(driversService.dataGrid(eqimInfo, ph));
grid.setTotal(driversService.Count(eqimInfo, ph));
return grid;
}
Grid.class contains private attributes including page, rows and rowsCount, and their getter and setter; Drivers.class is the data class.
I can confirm that the returned Grid instances contains every data retrieved from the database, but the strange thing is that every columns have their values shown except the "Device Name" column, which drives me crazy......
Any suggestions?
Problem solved. Turns out that the first letter of the field in mySQL should use lower cases, otherwise jsp would not recognize it.
I have a file containing of:
[{
'item1' : 'value1',
'item2' : [
'internalItem1' : 'value'
]
},
{
'item1' : 'value2',
'item2' : [
'internalItem1' : 'value',
'item2' : [
'internalItem1' : 'value',
'internalItem2' : 'value'
]
]
}]
I'd like to put it in an array of json objects. How can I do it? This is how I'm managing with a file containing of one JSON object:
$json = (Get-Content $fileLocation) | ConvertTo-Json
But the array of them is giving me nighthmares, how can I process this data?
Looks like you need commas on the end of the lines:
[{
'item1' : 'value1',
'item2' : {
'internalItem1' : 'value'
}
},
{
'item1' : 'value2',
'item2' : {
'internalItem1' : 'value',
'item2' : [{
'internalItem1' : 'value',
'internalItem2' : 'value'
}]
}
}]
I have an extJs(3.0) grid panel whick is loaded from postgresql database using json. This is my grid panel code segment:
var drop_pick_grid = new Ext.grid.GridPanel({
store : dropPickGridStore,
cm : new Ext.grid.ColumnModel([ selectModel, {
sortable : true,
header : "Drop/Pick Loc",
dataIndex : 'locationName',
width : 170
}, {
header : "Town/City",
sortable : true,
dataIndex : 'city',
width : 120
}, {
header : "Address",
sortable : true,
dataIndex : 'addr',
width : 170
}, {
header : "EST.Un/Load Time",
sortable : true,
dataIndex : 'estimatedTime',
width : 100
} ]),
sm : selectModel,
/*viewConfig: {
getRowClass: function(record, index) {
var color = record.get('tourTypeColor');
if (c == 'Kandy') {
alert('Kandy');
}
}
},*/
//width : 570,
//height : 390,
autoHeight : true,
autoWidth : true,
frame : true,
iconCls : 'icon-grid',
renderTo : document.body
});
My Json data :
{'dropPickLoc':[{ 'locationName' : 'Gayan Hardware', 'city' : 'Galle', 'addr' : '121, Wijaya Rd, Galle', 'estimatedTime' : '120', 'tourTypeColor' : 'blue' } , { 'locationName' : 'Kandy Hardware', 'city' : 'Kandy', 'addr' : '11, Kurunagala Road, Kandy', 'estimatedTime' : '40', 'tourTypeColor' : 'blue' } , { 'locationName' : 'Mala Stores', 'city' : 'Colombo', 'addr' : '11B, Thimbirigasyaya, Colombo', 'estimatedTime' : '45', 'tourTypeColor' : 'yellow' } , { 'locationName' : 'Namal Ceramic', 'city' : 'Kurunagala', 'addr' : '12B, Lumbini Udyanaya, Kurinagala', 'estimatedTime' : '45', 'tourTypeColor' : 'yellow' } , { 'locationName' : 'Priya Ceramic', 'city' : 'Nugegoda', 'addr' : '15, Nugegoda', 'estimatedTime' : '40', 'tourTypeColor' : 'yellow' } , { 'locationName' : 'Sam Stores', 'city' : 'Galle', 'addr' : '46A, Galle', 'estimatedTime' : '120', 'tourTypeColor' : 'green' } , { 'locationName' : 'Saman Stores', 'city' : 'Polgahawela', 'addr' : '111, Kurunagala Rd, Kurunagala', 'estimatedTime' : '120', 'tourTypeColor' : 'blue' } , { 'locationName' : 'Sell-X Computors', 'city' : 'Ratnapura', 'addr' : '12, Tiriwanakatiya, Ratnapura', 'estimatedTime' : '120', 'tourTypeColor' : 'green' } , { 'locationName' : 'Super Stores', 'city' : 'Kandy', 'addr' : '16, Kandy Road', 'estimatedTime' : '120', 'tourTypeColor' : 'blue' } , { 'locationName' : 'Wijesingha Hardware', 'city' : 'Galle', 'addr' : '113A, Wackewella Road, Galle', 'estimatedTime' : '120', 'tourTypeColor' : 'green' } ]}
The grid is loaded successfully. Now I need to change background color of "Location Name" column. According to my Json data every location name has a tourTypeColor. I need to change each and every location name cell according to this color.
Any suggestions are appreiated. please help me with some code segments.
Thanks a lot
I'm not that firm in using ExtJS 3.
I would try to define a rendere for your column "Drop/Pick Loc" like this:
{
sortable : true,
header : "Drop/Pick Loc",
dataIndex : 'locationName',
width : 170,
renderer : function(value, metaData, record, rowIndex, colIndex, store) {
metaData.attr = 'style="color:' + record.get('tourTypeColor') + ';"';
return value;
}
}
a simple table contains - id, name, text.
I need to bring these data in the grid with the grouping by the field name.
In all the examples that I found (for example - paper) uses the variable already defined the data. And I need to get data from Store.
ExtJs 3
The code:
Ext.onReady(function() {
var store = new Ext.data.JsonStore({
url : 'get_from_db.php',
storeId : 'MyStore',
totalProperty : 'totalCount',
idProperty : 'id',
remoteSort : true,
fields : [
{name : 'id', type : 'int'},
{name : 'name', type : 'String'},
{name : 'text', type : 'String'}
]
});
store.load();
var TestReader = new Ext.data.JsonReader({
idProperty : 'id',
fields : [
{name : 'id', type : 'int'},
{name : 'name', type : 'String'},
{name : 'text', type : 'String'}
]
});
var TestStore = new Ext.data.GroupingStore({
reader : TestReader,
data : 'get_from_db.php',
sortInfo : {
field : 'id',
direction : 'ASC'
},
groupField : 'name'
});
var TaskGrid = new Ext.grid.GridPanel({
store : TestStore,
columns : [
{id : 'id', header : 'Id', dataIndex : 'id'},
{id : 'name', header : 'Name', dataIndex : 'name'},
{id : 'text', header : 'Text', dataIndex : 'text'}
],
view : new Ext.grid.GroupingView({
forceFit : true,
groupTextTpl : '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
}),
frame : true,
width : 700,
height : 450,
collapsible : true,
animCollapse : false,
title : 'Grouping',
renderTo : document.body
});
});
As a result, output grid without a single error, the group is - but here's the column values - all zeros
post the code of 'get_from_db.php', if you can, please.
$connect = mysql_connect('localhost', 'root', ''); if ($connect) mysql_select_db('grid') or die('error with select table'); $select = mysql_query("select * from test"); while ($rec = mysql_fetch_array($select)) $rows[] = $rec; echo json_encode($rows);
You made mistake in returning JSON. Instead
$rows[] = $rec;
you need
$rows[] = array ("id"=>$rec['id'], "name"=>$rec['name'], "text"=>$rec['text']);
decided. code:
Ext.onReady(function() {
var TestStore = new Ext.data.GroupingStore({
url : 'http://extjs/get_from_db.php',
autoLoad : true,
remoteGroup : true,
groupField : 'name',
sortInfo : {
field : 'id',
direction : 'ASC'
},
reader : new Ext.data.JsonReader({
totalProperty : 'totalCount',
root : 'items',
idProperty : 'id',
fields: [
{name : 'id', type : 'int'},
{name : 'name', type : 'String'},
{name : 'text' ,type : 'String'}
]
})
});
var TaskGrid = new Ext.grid.GridPanel({
store : TestStore,
colModel : new Ext.grid.ColumnModel({
columns : [
{id : 'id', header : 'Id', dataIndex : 'id'},
{header : 'Name', dataIndex : 'name'},
{header : 'Text', dataIndex : 'text'}
],
defaults : {
sortable : true,
menuDisabled : false,
width : 20
}
}),
view : new Ext.grid.GroupingView({
startCollapsed : true,
forceFit : true,
groupTextTpl : '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
}),
frame : true,
width : 700,
height : 450,
collapsible : true,
animCollapse : false,
title : 'Grouping',
renderTo : document.body
});
});
More details in this note