html5 local storage value - html

Say I have the following for storing in a localstorage
var storageObject = {};
storageObject.value = myvalue;
storageObject.timestamp = d.getTime();
localStorage.setItem(myref, JSON.stringify(storageObject));
How do I use the getItem to retreive the value?

Simply:
localStorage.getItem(myref);
Or even:
localStorage[myref];
https://developer.mozilla.org/en/DOM/Storage#localStorage
Edit to restore original object from JSON, simply parse it:
var revivedObject = JSON.parse( localStorage.getItem(myref) );
// console.log(revivedObject);

Related

Adding Fields to JSON in better way Javascript

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.

Creating a zip file from a JSON object using adm-zip

I'm trying to create a .zip file from a JSON object in Node.js. I'm using adm-zip to do that however I'm unable to make it work with this code:
var admZip = require('adm-zip');
var zip = new admZip();
zip.addFile(Date.now() + '.json', new Buffer(JSON.stringify(jsonObject));
var willSendthis = zip.toBuffer();
fs.writeFileSync('./example.zip', willSendthis);
This code creates example.zip but I'm not able to extract it, I tried with a .zipextractor but also with this code:
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.data.toString('utf8'));
});
It returns Cannot read property 'toString' of undefined at the line with console.log.
I could use zip.writeZip() for this example but I'm sending the .zipfile to Amazon S3 thus I need to use the method .toBuffer() to do something like this after using adm-zip:
var params = {Key: 'example.zip', Body: zip.toBuffer()};
s3bucket.upload(params, function(err, data) {...});
I don't see what is wrong, am I using the package correctly?
Try use zipEntry.getData().toString('utf8') instead zipEntry.data.toString('utf8'):
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.getData().toString('utf8'));
});

ParseJSON with functions to javascript object

I have a problem that seems complicated that I don't know how to solve.
My single page application uses knockoutJS and I want to cache my view model every time one of my input values change on my view.
Where the problem lies is the complexity of my view model. To use local storage I need to stringify my object but it has recursive values. I have some logic to handle this and stringify my object. But when I try to parse the JSON string back to an object, I lose my functions.
function cacheForm(agency) {
//var serialized = stringifyOnce(agency);
//var serialized = amplify.store("Agency", agency);#
//var obj = new Object();
//obj.test = "test";
value = agency;
var cache = [];
parsed = JSON.stringify(value, function (key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
//var jsonString = JSON.stringify(cache);
//cache = null; // Enable garbage collection
var parsedRecursive = "{" + '"data"' + ":" + parsed + "," + '"expires"' + ":" + null + "}"; // Build the string based on how amplify likes it
var obj = eval('(' + parsed + ')')
var obj = jQuery.parseJSON(parsedRecursive);
//// Put the object into storage
//localStorage.setItem('Agency', parsedRecursive);
myData = JSON.parse(parsedRecursive, function (key, value) {
var type;
if (value && typeof value === 'object') {
type = value.type;
if (typeof type === 'string' && typeof window[type] === 'function') {
return new (window[type])(value);
}
}
return value;
});
//// Retrieve the object from storage
// var retrievedObject = localStorage.getItem('Agency');
// var obj = jQuery.parseJSON(parsedRecursive);
//var agency2 = mapping.fromJS(obj);
//agency;
//amplify.store("Agency", agency);
//amplify.store("Obj", obj);
//var store = amplify.store(); // Look at all items by not providing a key
}
});
I tried using eval but this returned an object without my data. To help you understand this is what my view model looks like, which is the agency parameter of cachForm.
Also I tried using amplify but because of my view model structure I run into the same issue.
I have also attached some screenshots to show what happens with my viewmodel in the code.
It is not a good idea to cache the whole viewModel. A viewModel contains observables, computeds and functions or events handlers.
You have better to cache the view model data, only the raw data.
On serialization :
So just serialize the view data (use ko.mapping.toJSON):
var json = ko.mapping.toJSON(viewModel);
In order to rebuild a proper view model it is better to have a initialisation function.
This is your view model constructor e.i. a function that adds the event handlers, functions and computed.
var initializer = your_constructor;
You also need to determine a cache key e.g. the page path.
var cacheItem = {data : json, constructor : initializer};
cache[key] = cacheItem;
On deserialization :
Get the cache item :
var cacheItem = cache[key];
var viewModel = JSON.parse(cacheItem.data);
Now viewModel contains the raw data.
viewModel = ko.mapping.fromJS(viewModel);
The properties were converted into observables.
If there is a constructor call it.
if(cacheItem.constructor)
cacheItem.constructor.call(viewModel);
Then your view model is as you stored it.
I hope it helps.
This is the answer I have posted in another post. They are both related.
JSON.parse returns children objects with null value, children values not being parsed

nodejs merge array

Im doint some nodejs fiddling with blogposts from wordpress and geotagging of theese posts. I have integrated geolite into nodejs and from wordpress i get the client id. Here is what my nodejs code looks like for now.
native.on('data',
function(data)
{
//console.log(data)
listener.sockets.emit('notification', data);
jsonstring = JSON.parse(data)
var ip = jsonstring.clientip
var geo = geoip.lookup(ip);
console.log(ip);
console.log(geo);
listener.sockets.emit('geodata', geo);
}
);
As you can see the lat / long is sent seperate from the json encoded data to the socket.
I want to merge the lat / long into "data" and sent is as 1 object. I cant figure out how to do this. i Hope someone can help me out with this.
An expando/ad-hoc property or two should suffice:
listener.sockets.emit('notification', data);
jsonstring = JSON.parse(data)
var ip = jsonstring.clientip
var geo = geoip.lookup(ip);
jsonstring.geo = geo;
// or
jsonstring.lat = geo.lat;
jsonstring.lng = geo.lng;
Add the geo information as another property of your parsed data object before emitting it:
native.on('data',
function(data)
{
var obj = JSON.parse(data)
obj.geo = geoip.lookup(obj.ip);
listener.sockets.emit('notification', JSON.stringify(obj));
}
);
You can also use
listener.sockets.emit('notification', data);
jsonstring = JSON.parse(data)
var ip = jsonstring.clientip
var geo = geoip.lookup(ip);
jsonstring['geo'] = geo;
to append the data in jsonstring
[ ] will be more helpful when we have dynamic key values

How to send array through HTTPservice in Adobe Flex 3

How to send array in Httpservice in Adobe Flex3
I am not quite sure what you mean by sending an array to a httpservice. If you mean to send an array to a httpservice with the same field name, you can pass an array as field value.
var service:HTTPService = new HTTPService();
service.useProxy = true;
service.destination = "myservicet";
service.resultFormat = HTTPService.RESULT_FORMAT_XML;
var fields:Array = ["categories", "organisation"];
var params:Object = new Object();
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field"] = fields;
service.send(params);
The HTTPService will convert this to the url parameters:
facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0
Hope this helps!
Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service
It really depends what is the back end technology you're using. If you're sending it to PHP you could try:
var fields:Array = ["categories", "organisation"];
var params:Object = {};
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field[]"] = fields;
service.send(params);
PHP will generate an array for you.
AFAIR this works fine in Rails as well.
if it is a simple string array, you can join it with a well know separator char, and on the other site, split the string with the same separator back to an array.
If it is a simple array, you could send it as a comma separated string.
httpService.request = new Object;
httpService.request.csv = array.toString();