I have a response json like this:
{
"variables": {
"lock": 0,
"pos": 55,
"pos_on": 55,
"pos_off": 150
},
"id": "11",
"name": "Lock_table_2",
"hardware": "esp8266",
"connected": true
}
and I try to show the lock value in 'variables' object
so I write
constructor(props) {
super(props)
this.state = {
dock_1: {}, // define a empty json
dock_2: {},
dock_3: {},
}
}
pingIP() {
axios
.get('http://192.168.50.225:8888/test_check')
.then(response => {
let data = response.data.list; // return value is a list
this.setState({ // every 2 sec setState
dock_1: data[0], // data[0] -> 192.168.50.40's json
dock_2: data[1],
dock_3: data[2],
})
})
}
render(){
return (
<p>{this.state.dock_1.variables.lock}</p>
);
}
but I got this error
in here
So I tried this
render(){
return (
<p>{this.state.dock_1.variables}</p>
);
}
then here comes the another error message
in here
here is the get request return value
{
"list": [
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_1",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_2",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
},
{
"connected": true,
"hardware": "esp8266",
"id": "10",
"name": "Lock_table_3",
"variables": {
"lock": 1,
"pos": 80,
"pos_off": 160,
"pos_on": 80
}
}
]
}
the return value is a list
in order to get first value so I wrote data[0], data1 ...
what's happening in here?
I think your response is an array of 3 items like this:
[
{
variables: {
lock: 0,
pos: 55,
pos_on: 55,
pos_off: 150
},
id: "11",
name: "Lock_table_2",
hardware: "esp8266",
connected: true
},
{
variables: {
lock: 1,
pos: 44,
pos_on: 56,
pos_off: 151
},
id: "11",
name: "Lock_table_3",
hardware: "esp8267",
connected: false
},
{
variables: {
lock: 2,
pos: 45,
pos_on: 57,
pos_off: 152
},
id: "11",
name: "Lock_table_4",
hardware: "esp8268",
connected: true
}
]
So you can access the dock 1 variable lock using Inline If with Logical && Operator to prevent null exception.
<p>{this.state.dock_1.variables && this.state.dock_1.variables.lock}</p>
A sample working codesandbox with a fake api:
https://codesandbox.io/s/stoic-chaplygin-r1yxd
I am new to JSON and mvc so here is my issue. I am currently working on graphs using highcharts. I have a controller which returns a JSON object.
public JsonResult _GetChart_TrendPublicationTypeDetailed_Data(int
yearToDisplay)
{
//Types of publications to be considered
string[] publication_types = new string[] { "article", "book", "book_section", "conference_proceedings" };
//Get the list of outputs with usp authors
var uspPubs = _uspAuthoredPublications();
//List of years for which to display the data
List<int> yearRange = _getListOfYears(yearToDisplay, yearRangeFactor_10);
//Get the data
var data = from eprint_summary in localDB.Summary
where
eprint_summary.Year > (yearToDisplay - yearRangeFactor_10)
&& eprint_summary.Year <= yearToDisplay
&& publication_types.Contains(eprint_summary.TypeCode)
&& uspPubs.Contains(eprint_summary.EprintId)
//&& eprint_summary.refereed == "TRUE" //TODO: Confirm whether we need this filter in our counts
group eprint_summary by new { eprint_summary.Year, eprint_summary.TypeDesc } into typeTrend
orderby typeTrend.Key.Year, typeTrend.Key.TypeDesc
select new
{
Year = typeTrend.Key.Year,
Type = typeTrend.Key.TypeDesc,
Count = typeTrend.Count()
};
//Extract the series data
List<object> countData = new List<object>();
foreach (var item in data.ToList().Select(y => y.Type).Distinct().OrderBy(y => y))
{
List<int> yearlyData = new List<int>();
foreach (var year in yearRange)
{
var rec = data
.Where(y => y.Type == item)
.Where(y => y.Year == year)
.Select(y => y.Count).ToArray();
yearlyData.Add(
rec == null || rec.Length == 0 ? 0 : rec[0]
);
}
countData.Add(
new
{
name = item, //Name of the series
data = yearlyData.ToArray() //Array of data
}
);
}
//Form the json object using the series data and labels
return Json(
new
{
labels = yearRange.ToArray(),
series = countData
},
JsonRequestBehavior.AllowGet
);
}
The above is my JSON in controller.
I have my view as below where I am getting the JSON object but I do not know how to append to my graph as series. How would I convert the JSON object to something that the series accepts.
var seriesData = ' ';
var test = ' ';
function ajaxCall() {
$.ajax({
type: "post",
datatype: "Json",
async: true,
url: '#Url.Action("_GetChart_TrendPublicationTypeDetailed_Data", "ResearchCharts")',
data: { yearToDisplay: '#(DateTime.Now.AddYears(-1).Year.ToString())' },
success: function (data) {
seriesData = data;
test = seriesData.series;
//bindChart(test);
//alert(JSON.stringify(seriesData));
alert(JSON.stringify(test));
},
error: function () {
alert("An error occurred.");
}
});
}
//functions call
ajaxCall();
bindChart(test);
function bindChart(test) {
var test2 = [{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }];
$('#chartTrendsPublicationTypeDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016']
},
series: test2//[{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }]
});
Please help, just need to somehow pass the data to highcharts.
in the picture, I have added the series manually and it works, but I need to pass in a variable which the series property accepts.
Old Highcharts rendering code:
$('#chartTrendsPublicationRankDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: labels
},
series: seriesData
});
New Highcharts rendering code. This accepts my JSON objects successfully and renders the graphs.
function bindChartItemType(seriesData, labels) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartTrendsPublicationTypeDetailed',
type: 'line',
height: 500,
width: 500
},
credits: {
enabled: false
},
title: {
text: 'Trend of Publications by Item Type'
},
xAxis: {
categories: labels,
title: {
text: '<b>Year</b>'
}
},
yAxis: {
min:0,
title: {
text: '<b># of publications</b>'
}
},
series: seriesData
});
}
Feel free to add anything you like in the comments.
Regards
Shafraz Buksh
I have a nested json for employee leaves and inside which i have leave history and leave eligibility. i need to populate two grids with the json.i can't read from the json or write to it..Please Help...
My Json is...
{
"EmployeeLeaves": {
"ID": 37,
"LeaveEligibility": [
{
"Availed": 4,
"Fullpaydays": 6,
"Halfpaydays": 0,
"ID": 1,
"LeaveTypeId": 60,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 2,
"Fullpaydays": 6,
"Halfpaydays": 0,
"ID": 3,
"LeaveTypeId": 61,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 10,
"Fullpaydays": 10,
"Halfpaydays": 0,
"ID": 4,
"LeaveTypeId": 62,
"PersonId": 37,
"YearOfLeave": 2013
},
{
"Availed": 0,
"Fullpaydays": 8,
"Halfpaydays": 0,
"ID": 6,
"LeaveTypeId": 63,
"PersonId": 37,
"YearOfLeave": 2013
}
],
"LeaveHistory": [
{
"AppliedTo": "Vibha",
"ApprovalDate": "3/12/2013 12:00:00 AM",
"ApprovedBy": 12,
"Duration": 3,
"FromDate": "3/24/2013 12:00:00 AM",
"FullPayDays": 3,
"HalfPayDays": 0,
"ID": 1,
"LeaveTypeId": 60,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "onnulla",
"StatusId": 79,
"SubstitutePersonId": 13,
"ToDate": "3/26/2013 12:00:00 AM"
},
{
"AppliedTo": "Vibha",
"ApprovalDate": "3/12/2013 12:00:00 AM",
"ApprovedBy": 12,
"Duration": 1,
"FromDate": "3/30/2013 12:00:00 AM",
"FullPayDays": 1,
"HalfPayDays": 0,
"ID": 2,
"LeaveTypeId": 60,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "onnulla",
"StatusId": 79,
"SubstitutePersonId": 13,
"ToDate": "3/31/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "",
"ApprovedBy": 0,
"Duration": 2,
"FromDate": "2/13/2013 12:00:00 AM",
"FullPayDays": 2,
"HalfPayDays": 0,
"ID": 4,
"LeaveTypeId": 61,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "blha blah",
"StatusId": 70,
"SubstitutePersonId": 1,
"ToDate": "2/14/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "2/13/2013 4:35:16 PM",
"ApprovedBy": 2,
"Duration": 5,
"FromDate": "3/23/2013 12:00:00 AM",
"FullPayDays": 5,
"HalfPayDays": 0,
"ID": 5,
"LeaveTypeId": 62,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "oh..",
"StatusId": 71,
"SubstitutePersonId": 1,
"ToDate": "3/27/2013 12:00:00 AM"
},
{
"AppliedTo": "Shyam",
"ApprovalDate": "2/13/2013 4:35:16 PM",
"ApprovedBy": 2,
"Duration": 5,
"FromDate": "3/28/2013 12:00:00 AM",
"FullPayDays": 5,
"HalfPayDays": 0,
"ID": 6,
"LeaveTypeId": 62,
"LossOfPayDays": 0,
"PersonId": 37,
"Remarks": "oh..",
"StatusId": 71,
"SubstitutePersonId": 1,
"ToDate": "3/29/2013 12:00:00 AM"
}
],
"PLavailedcount": 2
}
}
My Models and store are as follows....
Ext.define('custom.writer.Json', {
extend: 'Ext.data.writer.Json',
getRecordData: function(record) {
Ext.apply(record.data, record.getAssociatedData());
return record.data;
}
});
Ext.define('AM.store.LeaveRequest', {
extend: 'Ext.data.Store',
model: 'AM.model.leaverequest',
autoLoad:true,
proxy: {
type: 'ajax',
url:'ARSENAWeb/employeeleave.json?id=37',
reader: {
type: 'json',
root: 'EmployeeLeaves'
},
writer:new custom.writer.Json({writeAllFields: true}),
api: {
read: 'ARSENAWeb/employeeleave.json?id=37',
update: 'ARSENAWeb/employeeleave.json?id=37',
create:'ARSENAWeb/employeeleave.json?id=37'
}}
});
Ext.define('AM.model.leaverequest', {
extend: 'Ext.data.Model',
fields: ['ID' ],
idProperty: 'ID',
autoSync:true,
uses: ['AM.model.MLeaveHistory','AM.model.MLeaveStatus'],
hasMany: {model: 'MLeaveHistory',model:'MleaveStatus'},
save: function() {
var me = this;
if (me.persistAssociations) {
me.set( me.getAssociatedData() );
}
me.callParent(arguments);
}
});
Ext.define('AM.model.MLeaveHistory', {
extend: 'Ext.data.Model',
fields: [
{name:'ApprovalDate'},
{name:'ApprovedBy'},
{name:'Duration'},
{name:'FromDate'},
{name:'FullPayDays'},
{name:'HalfPayDays'},
{name:'ID'},
{name:'LeaveTypeId'},
{name:'LossOfPayDays'},
{name:'PersonId'},
{name:'Remarks'},
{name:'StatusId'},
{name:'SubstitutePersonId'},
{name:'ToDate'}
],
belongsTo: 'AM.model.leaverequest'
});
Ext.define('AM.model.MLeaveStatus', {
extend: 'Ext.data.Model',
fields: [ {name:'Availed'},
{name:'Fullpaydays'},
{name:'Halfpaydays'},
{name:'ID'},
{name:'LeaveTypeId'},
{name:'PersonId'},
{name:'YearOfLeave'}
],
belongsTo: 'AM.model.leaverequest'
});
My Controller is
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
stores: ['LType','SleaveHistory','SLeaveStatus',
],
models: [
'LeaveType','MLeaveHistory','MLeaveStatus'
],
views: [
'Leave.LeaveRequest','Leave.LeaveHistoryGrid','Leave.LeaveStatusGrid','Leave.HolidayList'
],
init: function() {
this.control({
'viewport >
'LeaveLeaveRequest button[action=reset]': {
click: this.resetForm
},
'LeaveLeaveRequest button[action=save]': {
click: this.saveForm
},
'leaveleavehistorygrid actioncolumn': {
itemclick: this.cancelLeave
},
'leaveleavehistorygrid': {
itemdblclick: this.editLeave
}
});
},
resetForm: function(button){
button.up('form').getForm().reset();
},
saveForm: function(button){
var form = button.up('form').getForm();
form.getValues(true);
var fromDate =new Date( Ext.getCmp('startdate'));//.getValue();
var endDate = new Date(Ext.getCmp('enddate'));
// var nod=Ext.Date.parseDate(fromDate,'m')
// Date.parseDate( String input, String format ) : Date
// var nod=fromDate+endDate;
var oneDay = 24*60*60*1000;
var diffDays = Math.round(Math.abs((fromDate.getTime() - endDate.getTime())/(oneDay)));
console.log(diffDays);
if (form.isValid()){
var record = form.getRecord();
var values = form.getValues();
// console.log(values);
if(!record){
var newRecord = new AM.model.leaverequest(values);
this.getLeaveRequestStore().add(newRecord);
}else {
record.set(values);
}}
} ,
cancelLeave: function (view, cell, rowIndex, colIndex, e, record, row) {
Ext.Msg.confirm('Remove Qualification', 'Are you sure?', function (button) {
if (button == 'yes') {
var store = Ext.getStore('LeaveRequest');
var newRecord = new AM.model.leaverequest(row);
console.log(record);
console.log(store);
store.remove(record);
store.sync();
}
}, this);
}
});
My Grids are:
Ext.define('AM.view.Leave.LeaveHistoryGrid' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.leaveleavehistorygrid',
title: 'Leave History',
store: 'LeaveRequest',
xtype: 'cell-editing',
plugins: [
Ext.create('Ext.grid.plugin.RowEditing', {
startEditByClick: function (){},
onEnterKey: function (){}
})
],
initComponent: function() {
this.cellEditing = new Ext.grid.plugin.CellEditing({
clicksToEdit: 1
});
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
this.columns= [
{header: 'Leave Type', dataIndex: 'LeaveTypeId',flex:1},
{header: 'Start Date', dataIndex: 'FromDate',renderer: Ext.util.Format.dateRenderer('m/d/y'),flex:1,editor: {
xtype: 'datefield',
forceSelection : true,
minValue: '01/01/06',
disabledDays: [0, 6],
allowBlank :false,
disabledDaysText: 'Plants are not available on the weekends'
}},
{header: 'End Date', dataIndex: 'ToDate',renderer: Ext.util.Format.dateRenderer('m/d/y'),flex:1, editor: {
xtype: 'datefield',
format: 'm/d/y',
minValue: '01/01/06',
disabledDays: [0, 6],
allowBlank :false,
disabledDaysText: 'Plants are not available on the weekends'
}},
{header: 'No of Days', dataIndex: 'Duration',flex:1},
// {header: 'Approval Status', dataIndex: 'leaveapprovalstatus',flex:1},
{header: 'Descriptions', dataIndex: 'Remarks',flex:1},
{header: 'Cancel Leave',flex:1,
xtype: 'actioncolumn',
width:30,
action:'cancel',
sortable: false,
items: [{
handler: function(view, cell, rowIndex, colIndex, e, record, row) {
this.addEvents('itemclick');
this.fireEvent('itemclick',view, cell, rowIndex, colIndex, e, record, row);
},
icon: 'ext-4.1.1a-gpl/ext-4.1.1a/docs/extjs/resources/themes/images/default/grid/page-first-disabled.gif',
tooltip: 'Cancel Leave'
}]
}]
this.callParent(arguments);
}
});
Ext.define('AM.view.Leave.LeaveStatusGrid' ,{
extend: 'Ext.grid.Panel',
alias: 'widget.leaveleavestatusgrid',
title: 'Leave History',
store: 'LeaveRequest',
initComponent: function() {
this.columns= [
{header: 'Type Of Leave', dataIndex: 'typeofleave',flex:1},
{header: 'Available', dataIndex: 'startdate',flex:1},
{header: 'Availed', dataIndex: 'leaveavailed',flex:1},
{header: 'Balance', dataIndex: 'leavebalance',flex:1}];
this.callParent(arguments);
}
});
my form
Ext.define('AM.view.Leave.LeaveRequest', {
extend: 'Ext.form.Panel',
alias: 'widget.LeaveLeaveRequest',
// requires: [
// 'Ext.ux.form.MultiSelect',
// ],
title: 'Leave Request',
// frame:true,
dockedItems: [{
dock: 'top',
xtype: 'toolbar',
items: [ {
text: 'Reset',
action: 'reset'
}, {
text: 'Save',
action: 'save'
}]
}],
initComponent: function() {
var required = '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>';
// var value,value1;
this.items = [{xtype:'fieldset',
layout:'hbox',
items:[{
xtype:'container',
layout:'anchor',
items:[{
xtype:'textfield',
fieldLabel : 'Type of Leave',
labelWidth:'130px',
allowBlank :false,
afterLabelTextTp1:required
},{
// xtype:'checkbox',
// boxLabel: 'Half Day ',
// name: 'durationofleave',
// inputValue: 'halfday',
// uncheckedValue: 'fullday',
// allowBlank :false,
// afterLabelTextTp1:required
// },{
xtype:'datefield',
//renderer: Ext.util.Format.dateRenderer('m/d/y'),
vtype:'daterange',
fieldLabel : 'From Date',
labelWidth:'130px',
id:'FromDate',
afterLabelTextTpl: required,
name : 'FromDate',
endDateField: 'ToDate',
//minValue: new Date(),
allowBlank :false,
afterLabelTextTp1:required
},{
xtype:'datefield',
vtype:'daterange',
renderer: Ext.util.Format.dateRenderer('m/d/y'),
fieldLabel : 'To Date',
id:'ToDate',
startDateField: 'FromDate',
labelWidth:'130px',
// onExpand: function() {
// var field = Ext.getCmp('startdate');
// value: field.getValue();
// value1 = this.getValue();
// console.log(value+value1);},
// minValue: new Date(getCmp('startdate')),//Ext.Date.add(new Date(), Ext.Date.DAY, 7) ,
afterLabelTextTpl: required,
name : 'ToDate',
// change: function() {
// value = this.getValue('startdate')
// //var value = this.getValue('startdate');
// console.log(value);
// //this.picker.setValue(Ext.isDate(value) ? value : new Date());
//},
allowBlank :false,
afterLabelTextTp1:required
},{
xtype:'textfield',
fieldLabel : 'Number of days',
labelWidth:'130px',
id: 'textfield-field',
afterLabelTextTpl: required,
name : 'noofdays',
allowBlank :false,
afterLabelTextTp1:required
},
{
// xtype: 'multiselect',
// labelWidth:'130px',
// fieldLabel: 'Reporting Manager(s)',
// name: 'reportingmanager',
// id: 'multiselect-field',
// forceSelection : true,
// allowBlank: false,
// store: 'ReportingManager',
// mode: 'local',
// displayField: 'reportingmanager',
// valueField: 'value',
// ddReorder: true,
// afterLabelTextTp1:required
// },{
xtype:'textfield',
fieldLabel : 'Reason',
labelWidth:'130px',
afterLabelTextTpl: required,
name : 'reason',
allowBlank :false,
afterLabelTextTp1:required
}]
},{xtype:'container',width:'300px'},
{
xtype:'container',
items:[{xtype:'leaveleavestatusgrid',
store: 'LeaveRequest',
height: 200,
width: 500
}]
}]
},{xtype:'fieldset',
title:'Leave History',
items:[{xtype:'leaveleavehistorygrid',
store: 'LeaveRequest',
height: 300,
width: '100%'
}]
}];
this.callParent(arguments);
}
});
My json has a little change where the curly braces has been replaced by square braces
{
"EmployeeLeaves": [
{
"ID": 0,
"LeaveHistory": {
"Duration": 2,
"ApprovedBy": "shyam"
},
"PL": "'I don't care!' said the bear"
}
]
}
My model for the same has been changed to
Ext.define('AM.model.EMPLeaveRequest', {
extend: 'Ext.data.Model',
fields: [{
name: 'ID'
}, {
name: 'Duration',
mapping: 'LeaveHistory.Duration'
}, {
name: 'ApprovedBy',
mapping: 'LeaveHistory.ApprovedBy'
}],
proxy: {
type: 'ajax',
batchActions: false,
url: 'data/employeeleave.json',
autoAppendParams: false,
reader: {
type: 'json',
root: 'EmployeeLeaves',
useSimpleAccessors: false
}
}
});
My store is
Ext.define('AM.store.EMPLeaveRequest', {
extend: 'Ext.data.Store',
model: 'AM.model.EMPLeaveRequest',
autoLoad: true//,
});
There is no need for using associations....But only works for one set of data :(