nodejs merge array - json

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

Related

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'));
});

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible

Binding JSON string to ListView in Metro apps?

I have a metro application(HTML5 & WinJS) in which am trying to display service data . Actually here am retrieving JSON data from my service but am unable to bind this data into listview . Anyone give me some working example.
Thank you.
You can use the WinJS.xhr() for this. You can read more about it on this link https://msdn.microsoft.com/pt-br/library/windows/apps/br229787.aspx and here is an example:
var path = "data/file.json";
function getData(path) {
WinJS.xhr({ url: path }).then(
function (response) {
var json = JSON.parse(response.responseText);
// Since this is an asynchronous function, you can't
// return the data, so you can:
// 1) retrieve the data to a namespace once the app loads.
var list = new WinJS.Binding.List(json);
Somenomespace.data = list;
// 2) or do all the binding inside the function.
var listView = document.getElementById("listViewID");
listView.winControl.itemDataSource = list.dataSource;
});
}
If you use the built in JSON.parse(jsonString) function you can loop through the content using a normal for loop as it then is a normal object and add it as usuall. Just remember to process or render the data.
Her is an example from code i had in a search page using listview:
var response = JSON.parse(data) ;
var originalResults = new WinJS.Binding.List();
for (x in response) {
originalResults.push(response[x]);
}
this.populateFilterBar(element, originalResults);
this.applyFilter(this.filters[0], originalResults);

html5 local storage value

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);

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();