I'm using Node-Red and the data is passed using JSON objects.
All of the data is in msg.payload. I want to add a new property, the TimeStamp, to the object without all of this unnecessary code...It works but I know this is sloppy.
Is there a better way?
var TimeStamp = new Date();
var newMsg = [ ];
newMsg.push({payload:
{ TimeStamp:TimeStamp ,
Humidity: msg.payload.Humidity,
Temperature: msg.payload.Temperature,
CO2: msg.payload.CO2,
Light: msg.payload.Light
}
});
return newMsg;
You can add the new property to the existing msg object and pass it on.
msg.payload.TimeStamp = new Date();
return msg;
This is the better approach as it leaves all other message properties untouched.
Related
I'm using the latest Haxe and HaxeFlixel to make a simple game prototype.
I have the following class...
class GameData
{
public var playerHealth: Int;
public var playerScore: Int;
public var levelName: String;
public function new(playerHealth: Int = 0, playerScore: Int = 0, levelName: String = "")
{
this.playerHealth = playerHealth;
this.playerScore = playerScore;
this.levelName = levelName;
}
}
I convert it to JSON as follows...
Json.stringify(new GameData(64, 512, "Level 1"));
Is there's a way I can make it so the stringify ignores certain members?
haxe.Json has no mechanism to exclude fields, so I would recommend using a third-party library such as json2object that does. Here you can simply annotate fields that should be ignored with #:jignored:
#:jignored
public var levelName:String;
var data = new GameData(100, 10, "Level 1");
var json = new json2object.JsonWriter<GameData>().write(data);
trace(json); // {"playerHealth": 100,"playerScore": 10}
There are some possible workarounds that don't involve adding a library to your project, but they don't seem very nice:
Don't serialize the object directly, but a structure that only includes the desired fields:
var data = new GameData(100, 10, "Level 1");
var json = Json.stringify({
playerHealth: data.playerHealth,
playerScore: data.playerScore
});
trace(json); // {"playerHealth":100,"playerScore":10}
Remove the unwanted fields after serialization - this seems rather hacky as it involves a lot of unnecessary overhead due to an additional Json.parse() and Json.stringify() call:
var json = Json.stringify(new GameData(100, 10, "Level 1"));
var data:haxe.DynamicAccess<String> = Json.parse(json);
data.remove("levelName");
json = Json.stringify(data);
trace(json); // {"playerHealth":100,"playerScore":10}
Depending on your exact situation, it can be desirable to make a slightly modified version of standard library's JsonPrinter - for example, in GMEdit I allow JSON objects to have an hxOrder: Array<String> field, which, if provided, determines the field order for printing, and is initialized to a static array. You can make a similar scheme for field inclusion/exclusion.
Trying to convert JSON data into int in order to perform calculations, multiply by numbers or percentages (or whichever method is best recommended)
Tried performing calculation on the object (using addition for example), but it only added numbers on to the end of the resulting string. I have seen suggestions on using JSON parse (reviver) but can't seem to get my head round getting the desired data when it is only one specific part of the JSON data required rather than multiple items of data from the JSON link.
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var gbpValue = "1 BTC equals to £" + json["bpi"]["GBP"]["rate"];
document.getElementById("data").innerHTML =
gbpValue;
As mentioned, have tried performing calculations on the result but it only adds numbers to the end of the string. Thanks for any advice or help.
What I can see in your code is that you are adding your json variable with a string which would always result in string concatenation in below line:
var gbpValue = "1 BTC equals to £" + json["bpi"]["GBP"]["rate"];
First check your json object if it a number or string.
You could use the Number() or parseInt() functions to convert a string to number.
Example:
var num=Number("23");
or
var num=parseInt("23");
Hope it helps. :)
I am currently trying to figure out how I can retrieve a single value from a sap.ui.model.json.JSONModel
in my main view:
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
};
oController.getConfiguration(getConfigCallback);
console.log(gConfigModel);
in my controller:
getConfiguration : function(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
callback(config);
$.getJSON(sServiceUrl).done(function(data) {
config = data.d;
callback(config);
});
},
In my console.log statement I can see that the data was successfully passed from the backend and successfully set to the JSON model. My requirement is to store the value of attribute Editable in a single variable.
I already tried gConfigModel.getProperty('/'), didnt work. tried to access gConfigModel.oData was undefined .. How can I store it in a single value?
Solution Comment: If you catch data from a backend, you have to take care how long it takes. data can be available later then expected, in my case I added 1s timeout, afterwards I can access the property easily
setTimeout(function() {
console.log(gConfigModel.getProperty('/Editable'));
}, 1000);
I wouldn't advise using the model's getData() method since it is deprecated.
A much better solution is to use gConfigModel.getProperty("/Editable")
(I'm using the root slash here since your property resides in the root of your model)
In the same way, you can also set your data:
gConfigModel.setProperty("/Editable", <your new value>) instead
First of all, thanks for the effort to find solutions of our Problems! (at least, those regarding It stuff.. :) )
I've found a solution which I think is a little bit more save because the timeout is maybe somewhat arbitrary - it would depend on the machine or the amount of data that is to be fetched?
Therefore, I am using an attachRequestCompleted function:
with sUrl_2="path-to-my-service";
var oModel_2 = new sap.ui.model.json.JSONModel(sUrl_2);
oModel_2.attachRequestCompleted(function(data) {
//now, i can access the data stored in the oModel_2, either by getProperty, or by DOM: oModel_2.oData.d.Vendor
gv_selLieferant = oModel_2.getProperty("/d/Vendor");
gv_selEinkOrg = oModel_2.getProperty("/d/PurchOrg");
gv_selEinKGru = oModel_2.getProperty("/d/PurGroup");
});
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap" data-sap-ui-theme="sap_bluecrystal" data-sap-ui-libs="sap.m"></script>
<script>
function getConfiguration(callback) {
var sServiceUrl = "/sap/opu/odata/sap/xxx/ConfigurationSet('Initialize')";
var config = {};
var data = {
"d": {
"_metadata": "",
"Backup01": "01",
"Editable": "True"
}
};
setTimeout((function() {
config = data;
callback(config);
})(), 2000);
};
var gConfigModel = new sap.ui.model.json.JSONModel();
var getConfigCallback = function(config) {
gConfigModel.setData(config);
alert(gConfigModel.getProperty("/d/Editable"));
};
getConfiguration(getConfigCallback);
</script>
Here's what I have mocked out of my MVC code:
$(function(){
var ViewModel = function(){
this.items = ko.observableArray(null);
this.isLoading = ko.observable(true);
};
var data = [{"CreatedAt":"2013-12-29T22:00:20","Intro":"","Body":"","Title":"Test Item","Url":"/news-items/test-item/"},{"CreatedAt":"2013-12-29T21:13:34","Intro":"","Body":"","Title":"Test 1","Url":"/news-items/test-1/"},{"CreatedAt":"2013-12-29T16:03:56","Intro":"","Body":"<p>In the spirit of Christmas we are holding a Christmas photo competition for all members to enter. Prizes will be given to the best Christmas themed photo and the funniest photo. To enter, simply email your photo to: competition#bernese.org.nz. Your entry will be uploaded onto the club's Facebook page where all members can then vote by 'liking' their favourite photo.</p>\n<p>Entries close on the 20th of December and voting will be open until the 5th of January. The winning photo's will be displayed on the website.</p>","Title":"Christmas 2013 Photo Competition","Url":"/news-items/christmas-2013-photo-competition/"}];
var vm = new ViewModel();
ko.applyBindings(vm);
vm.items(test);
vm.isLoading(false);
})
I have mocked it from my MVC code, but the data object is basically what was returned from my controller. Knockout mapping is not working in this case and I suspect it's the way my data is returned. Is this a valid way, or do I need to wrap it in a DTO of sorts, e.g.: { items: [{item1:'...'},{item2:'...'}]}?
Thanks.
EDIT:
My mistake, I already defined items as observableArray. I use it this way so as soon as the page loads the loader gif is displayed. I have done it this way before, the only difference this time being the format of the json returned.
ADDED: Here's the example
I don't know if this is the only problem, but
this.items = ko.observable(null);
should be
this.items = ko.observableArray();
But I probably do the whole thing more like
$(function(){
var ViewModel = function(items){
this.items = ko.observableArray(items);
};
var data = [...];
var vm = new ViewModel(data);
})
UPDATE: Here is a fully working jsfiddle
The ko.mapping.fromJS(data) returns a ko.observableArray if the data parameter is already an array.
So you need to unwrap the returned ko.observableArray before assigning it:
var vm = new ViewModel();
ko.applyBindings(vm);
var test = ko.mapping.fromJS(data);
vm.items(test()); // you need to write `test()` to get the underlaying array.
Or you can directly fill in your already declared ko.observableArray with writing:
var vm = new ViewModel();
ko.applyBindings(vm);
ko.mapping.fromJS(data, {} /* mapping options */, vm.items);
Here is your updated JSFiddle.
i'm making a todolist in mootools and having the following problem. i'm store my todo items in a cookie but the issue is i can't read how many cookies i've set so i can get the value of them.
my question is: is there any way to count how many cookies i've so i can loop trough them and get the correct value.
when i put the getData in a console.log i'm getting my json but i also can't read the values from there. what am i doing wrong and wich other implementation do u advise me.
tnx in advance.
for now i've the following code.
window.addEvent('domready', function(){
$('add').addEvent('click', function(){
var value = $('todo').value;
var t = new Todo(value,"beschrijving",new Date(),1);
var storeData = JSON.encode(t);
var c = Cookie.write(value,storeData,{duration:1});
var getData = Cookie.read(value);
console.log(getData);
});
});
var Todo = new Class(
{
initialize: function(title,description,date,isDone){
this.title = title;
this.description = description;
this.date = new Date();
this.isDone = isDone;
},
getTitle:function()
{
return this.title;
},
getIsDone:function()
{
return this.isDone;
},
setIsDone:function(value)
{
this.isDone = value;
},
});
You seem to be missing the core point of cookies - when you set a cookie with a specified name, it overwrites the previous value of that cookie. With your current approach, it will never contain more than a single item.
You have to keep an array of todo items and serialize and store that array instead of the Todo object itself.
Also, you'll grow out of max cookie size quickly this way. I'd recommend using HTML5 LocalStorage instead. A base wrapper of LocalStorage can be found in Mootools Powertools.