can't access nested JSON - json

When I try to display the object using console log, I am getting undefined. The line of code is:
var inform = data.Payload;
// If access allowed, set redirect location
console.log(inform.token_use);
The data is a JSON object with the following values:
{
"StatusCode": 200,
"Payload": "{\"sub\":\"1234567-1234-1234-1234-123456778\",\"token_use\":\"access\",\"scope\":\"aws.cognito.signin.user.admin\",\"iss\":\"https://cognito-idp.us-east-1.amazonaws.com/us-east-1_99999999999\",\"exp\":1468310126,\"client_id\":\"xxxxxxxxxxxxx\",\"username\":\"usernam\"}"
}
I wanted to check the value of token_use.

var inform = JSON.parse(data.Payload);
You need to parson payload since its stringify

'1234567-1234-1234-1234-123456778','token_use' => 'access');
$json_data= json_encode($data);
?>
var data= '';
var res = JSON.parse(data);
var inform = res.Payload;
console.log(inform.token_use);

Related

Unexpected character encountered while parsing value <. Path '', line 0, position 0

I'm trying to use the Bing api. Problem is I keep getting an error of "Unexpected character encountered while parsing value: <. Path '', line 0, position 0." Specifically at the JObject.Parse
Here is my code:
public async Task<CoordServiceResult> LookUp()
{
var result = new CoordServiceResult();
var location = "seattle";
var key = "MyBingKey"
var url = "http://dev.virtualearth.net/REST/v1/Locations?q=" + location + "&output=xml&key=" + key;
var client = new HttpClient();
var json = await client.GetStringAsync(url);
var results = JObject.Parse(json);
var resources = results["resourceSet"][0]["resources"];
var coords = resources[0]["geocodePoints"][0]["coordinates"];
result.Lat = (double)coords[0];
result.Long = (double)coords[1];
return result;
}
I was also looking at this link Error Parsing Json but it didnt work either. Any suggestions?
Thanks
You are requesting the data as XML not JSON.
&output=xml
Remove this parameter to get a JSON response.
https://msdn.microsoft.com/en-us/library/ff701710.aspx states a JSON response is provided when the output (o) parameter is not set.

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 update existing json object in java script with titanium studio

var args = arguments[0] || {};
$.atn.text=args.attendance;
Ti.API.info('attendance:'+args.attendance);
function doClick(e){
$.atn.value=$.atn.value+1;
Ti.API.info('atn is'+$.atn.value);
var url = "api.usergrid.com/PRI_95616/LOGIN/attendances?";
var client = Ti.Network.createHTTPClient({
onload : function(e) {},
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
client.setRequestHeader('content-type', 'JSON');
client.open("PUT", url);
client.send(JSON.stringify(jsonobject));
}
I want to fetch and then update the attendance value then insert the updated value in database. How can I do it?
If by "update the database" you mean PUT to the Restful API, then you have one small error.
client.send(JSON.stringify(jsonobject));
jsonobject is not defined. It must be the json (JavaScript) object you just built. if $.atn is the object you're pushing values into then try:
client.send(JSON.stringify($.atn));
I don't know the REST API specs for usergrid.com, but if all you have to do is PUT a json object with .text and .value defined, the URL "api.usergrid.com/PRI_95616/LOGIN/attendances?" then this should do it. However, you'll have to put http:// before the URL like:
"http://api.usergrid.com/PRI_95616/LOGIN/attendances?"

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

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