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.
Related
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);
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'));
});
I am new to IronJS and facing difficulty parsing JSON in JavaScript method.
My C# Code
string jsonString = "{\"Name\": \"Ankur\", \"Sex\": \"Male\"}";
var o = new IronJS.Hosting.CSharp.Context();
o.ExecuteFile(#"C:\CustomScript.js");
var handleJson = o.Globals.GetT<FunctionObject>("HandleJson");
var result = handleJson.Call(o.Globals, jsonString).Unbox<string>();
Console.WriteLine(result);
JavaScript method in CustomScript.js
function HandleJson(jsonStr) {
obj = JSON.parse(jsonStr);
return obj.Name;
}
Everytime I do this, I get error message saying "ReferenceError: JSON is not defined"
Guess, "JSON.parse" method is native to browser and which isn't available server side.
I can use jQuery method obj = $.parseJSON(jsonStr); as well but don't know how to load jQuery file.
Any thoughts on what I am doing wrong or how to fix it?
Thanks.
I have found the fix to it.
JSON.parse is an unknown JS method at Server(which is why we were getting the error)... So, we need to add/load "json2.js" before CustomScript.js file and then we will be good.
json2.js can be downloaded from following location: https://github.com/douglascrockford/JSON-js
Following is my updated code.
Updated C# Code
string jsonString = "{\"Name\": \"Ankur\", \"Sex\": \"Male\"}";
var o = new IronJS.Hosting.CSharp.Context();
o.ExecuteFile(#"C:\json2.js");
o.ExecuteFile(#"C:\CustomScript.js");
var handleJson = o.Globals.GetT<FunctionObject>("HandleJson");
var result = handleJson.Call(o.Globals, jsonString).Unbox<string>();
Console.WriteLine(result);
No changes are required in CustomScript.js
Cheers!
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
supposed i have this JSON, and supposed the properties may change...
'{"srcLocation":"pc","filename":"name","fileext":"jpg","url":""}';
first I want to get all the properties on them (srcLocation, filename etc)
and using the properties I got I want to get the corresponding value..
how can I do that in action script?
First of all you need to decode the JSON, probably using as3corelib:
var jsonString:String = '{"srcLocation":"pc","filename":"name","fileext":"jpg","url":""}';
var decodedObj:Object = JSON.decode(jsonString);
Then all you have to do is loop through the object to get all the name/value pairs:
for(var key:String in decodedObj) {
trace("Name: " + key + " - Value: " + decodedObj[key];
}
Which will output:
Name: srcLocation - Value: pc
Name: filename - Value: name
Name: fileext - Value: jpg
Name: url - Value:
First you should load the JSON file using URLLoader and then decode the data into Object
and after that you will be able to get the corresponding value of the properties of that
Object:
var myRequest:URLRequest = new URLRequest("Your JSON file Name");
var myLoader = new URLLoader();
myLoader.addEventListener(Event.COMPLETE, onload);
myLoader.load(myRequest);
function onload(evt:Event):void
{
var myData:Object = JSON.decode(myLoader.data);
trace(myData.firstName);
trace(myData.job);
trace(myData.age);
}
for any further help go through this link:
http://swati61.blogspot.com/2011/06/json-and-as3-communication.html
I suggest you use Adobe's Native JSON decoding.