How to JSON parse in windows 8 - javascript

I am doing a winJS.xhr like this :
var jsonResult;
WinJS.xhr(
{
url: urlGoogle,
responseType: 'json'
}
).done(function complete(response) {
jsonResult = response.responseText;
console.log(jsonResult);
},
//Error and Progress functions
);
The console log shows me this :
{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}
And I want to get the rhs info.
So I tried doing
console.log(jsonResult.rhs);
and
console.log(jsonResult['rhs']);
It only shows me "undefined". Then I realized that when I did a jsonResult[0], it shows me the first character (which is { ) and so on with the index bracket.
I tried to do a JSON.parse(jsonResult); but it creates an error
json parse unexpected character

The string you are seeing isn't actually valid JSON as it's property names are not quoted. That is why JSON.parse is throwing an error.

Just tried it on Chrome Dev Tools:
JSON.parse("{lhs: \"32 Japanese yen\",rhs: \"0.30613818 Euros\",error: \"\",icc: true}")
SyntaxError: Unexpected token l
JSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}')
SyntaxError: Unexpected token l
JSON.parse('{lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: 1}')
SyntaxError: Unexpected token l
JSON.parse('{"lhs": "32 Japanese yen","rhs": "0.30613818 Euros","error": "","icc": true}')
Object
error: ""
icc: true
lhs: "32 Japanese yen"
rhs: "0.30613818 Euros"
__proto__: Object
So it seems a "valid" JSON string should use double quote " to enclose every possible place.
Actually this also happens on PHP's json_decode.
I don't know about Win8JS development, so I'm not sure if you can use response.responeJSON or something like that, but directly parsing response.responseText seems likely to fail.
If you really need to use the responseText, consider #Cerbrus' dangerous eval method.

var test = {lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true}
//test.lhs returns "32 Japanese yen"
I am not quite sure why this isn't working for you. Try logging the console.log(typeof jsonResult) to see if the jsonResult is a string or a object. (if it were a string, I'd say JSON.parse should've worked)
Then log jsonResult itself, and see if you can walk through it's properties.
(The google chrome console works like a charm for this)
In case it is a string, this is a (Somewhat hacky, unsafe) way to do it:
var result = eval('({lhs: "32 Japanese yen",rhs: "0.30613818 Euros",error: "",icc: true})')
var result = eval('(' + jsonResult + ')')
(Thanks to #ThiefMaster♦ for some more proper(-ish) use of eval instead of my own abuse of it.)
You should then be able to access result
Generally, you don't want to use eval, but if all else fails...

In your case ,Check the following
WinJS.xhr({ url: urlGoogle }).then(
function completed(response) {
var jsonString = JSON.parse(response.responseText);
console.log(jsonString .rhs);
},
function error(error) { console.log(error) },
function progress(progress) { }
);
OR
WinJS.xhr({ url: urlGoogle }).then(
function completed(response) {
var jsonString = JSON.parse(response.responseText);
console.log(jsonString .rhs);
},
function error(error) { console.log(error) },
function progress(progress) { }
);

First do:
jsonResult = JSON.parse(response.responseText);
and then you can use:
var rhs = jsonResult.rhs;

I have blogged about this in the past. The code below calls into a web service that returns JSON.
It is explained here:
http://blogs.msdn.com/b/brunoterkaly/archive/2012/11/06/step-4-augmented-reality-windows-8-and-cloud-computing-how-to-implement-with-real-code-implementing-the-windows-8-client.aspx#
What is useful about this code is that you "try" to get the values. They may not exist.
See parsedResults.TryGetValue().
private async System.Threading.Tasks.Task CallLocationWebService(string gps)
{
// Call into the emulator. This assumes you are running the
// cloud project from the last post in the backgruond
string _location = "http://127.0.0.1:81/api/values?location={0}";
// You can use the line below once you deploy your cloud
// application to the cloud (a MS data center)
//string _location = "http://locationwebservice.cloudapp.net/api/values?location={0}";
// Now make the aynchronous call. We need to pass the GPS
// parameters here to the _location string mentioned above.
using (HttpClient clientlocation = new HttpClient())
using (var response = await clientlocation.GetAsync(string.Format(_location, gps)))
{
if (response.IsSuccessStatusCode)
{
string webresponse = await response.Content.ReadAsStringAsync();
// Parse the string into a JSONObject
var parsedResults = JsonObject.Parse(webresponse);
IJsonValue val;
// Extract data embedded in JSONObject.
// Assign to controls in user interface
if (parsedResults.TryGetValue("latitude", out val))
loc_info.latitude = val.GetString();
if (parsedResults.TryGetValue("longitude", out val))
loc_info.longitude = val.GetString();
if (parsedResults.TryGetValue("bus_and_neighborhood", out val))
loc_info.bus_and_neighborhood = val.GetString();
if (parsedResults.TryGetValue("elevation", out val))
loc_info.elevation = val.GetString();
if (parsedResults.TryGetValue("bus_and_neighborhood", out val))
loc_info.bus_and_neighborhood = val.GetString();
if (parsedResults.TryGetValue("max_temp", out val))
loc_info.max_temp = val.GetString();
if (parsedResults.TryGetValue("min_temp", out val))
loc_info.min_temp = val.GetString();
this.bus_and_neighborhood.Text = loc_info.bus_and_neighborhood;
this.elevation.Text = loc_info.elevation;
this.latlong.Text = loc_info.latitude + "/" + loc_info.longitude;
this.max_temp.Text = loc_info.max_temp;
this.min_temp.Text = loc_info.min_temp;
}
}
}

Related

How to apply regular expression for Javascript

I am trying to get message log from Azure application Insight like this
az monitor app-insights --app [app id] --analystics-query [condition like specific message id]
Then I got a message like this
"message": [
"Receiving message: {"type":"CTL","traceId":"f0d11b3dbf27b8fc57ac0e40c4ed9e48","spanId":"a5508acb0926fb1a","id":{"global":"GLkELDUjcRpP4srUt9yngY","caller":null,"local":"GLkELDUisjnGrSK5wKybht"},"eventVersion":"format version","timeStamp":"2021-10-01T14:55:59.8168722+07:00","eventMetadata":{"deleteTimeStamp":null,"ttlSeconds":null,"isFcra":null,"isDppa":true,"isCCPA":true,"globalProductId":null,"globalSubProductId":null,"mbsiProductId":null},"eventBody":{"sys":"otel","msg":"Testing Centralized Event Publisher with App1 (using logback)","app":{"name":"otel","service":"postHouse","status":"status name","method":"POST","protocol":"HTTP","resp_time_ms":"250","status_code":"4"},}}"
] }
So that I would like to apply Regular Expression for this message to get only the message from {"type.....to "status_code":"4"},}} and also convert it to JSON format
I have code like this in my .js file
Then('extract json from {string}', function(message){
message = getVal(message, this);
const getmess = message.match(/{(.*)}/g);
const messJson = JSON.parse(getmess);
console.log(messJson);
})
But it doesn't work for me
SyntaxError: Unexpected token \ in JSON at position 1
How can I apply this in my code on Javascript? Thank you so much for your help
Try this. But keep in mind, that current regex is binded with provided program output syntax. If output will be different in wrapper structure, this regex might not work any more.
// Text from app
const STDOUT = `
"message": [ "Receiving message: {"type":"CTL","traceId":"f0d11b3dbf27b8fc57ac0e40c4ed9e48","spanId":"a5508acb0926fb1a","id":{"global":"GLkELDUjcRpP4srUt9yngY","caller":null,"local":"GLkELDUisjnGrSK5wKybht"},"eventVersion":"format version","timeStamp":"2021-10-01T14:55:59.8168722+07:00","eventMetadata":{"deleteTimeStamp":null,"ttlSeconds":null,"isFcra":null,"isDppa":true,"isCCPA":true,"globalProductId":null,"globalSubProductId":null,"mbsiProductId":null},"eventBody":{"sys":"otel","msg":"Testing Centralized Event Publisher with App1 (using logback)","app":{"name":"otel","service":"postHouse","status":"status name","method":"POST","protocol":"HTTP","resp_time_ms":"250","status_code":"4"},}}"
] }
`;
// Match JSON part string
let JSONstr = /.*\[\s*\"Receiving message:\s*(.*?)\s*\"\s*]\s*}\s*$/.exec(STDOUT)[1];
// Remove trailing comma(s)
JSONstr = JSONstr.replace(/^(.*\")([^\"]+)$/, (s, m1, m2) => `${m1}${m2.replace(/\,/, "")}`);
// Convert to object
const JSONobj = JSON.parse(JSONstr);
// Result
console.log(JSONobj);
Try this one:
/.*?({"type":.*?,"status_code":"\d+"\})/
When used in Javascript, the part covered by the parentheses counts as Group 1, i.e.,:
const messJson = JSON.parse(message.match(/.*?({"type":.*?,"status_code":"\d+"\})/)[1]);
Reference here: https://regexr.com/66mf2

Console log ({value}) isn't the same as console.log(value)

I'm not stuck or anything, it's just my own curiosity and I noticed something about Console.log,
And I can't find anwsers online , or its limited since I think making a Google search with "{}" isn't really working out
I'm coding a small node.Js app that interacts with Wi-Fi, and I tried the following thing :
console.log(ssid + " : " + pwd);
and it returns this
freebox_XXXXX : fake_password
So far, everything is normal but then, I was tired and messed up and tried this :
console.log({ ssid: ssid, password: pwd });
and it returned this
{
ssid: 'f\x00r\x00e\x00e\x00b\x00o\x00x\x00_\x005\x007\x00a\x002\x00a\x007\x00',
password: '\x00T\x00e\x00s\x00t\x00'
}
I'm wondering why do you have any answers?
More details :
The data sent via bluetooth by this function as an bufferArray is created with this function
str2ab(str) {
let buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
let bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
let payload = str2ab('freebox_XXXXX|' + alertData.password);
Then, the other devices receives it
WriteOnlyCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
let payload = data.toString()
let wifiData = payload.split('|');
let ssid = wifiData[0];
let pwd = wifiData[1];
console.log(ssid + " : " + pwd);
console.log({ ssid: ssid, password: pwd });
});
The difference is because of how Node.js logs values.
The behaviour of console.log() depends on the type of values being logged:
If a string is logged, it is written to stdout as-is (well, not as-is, because %-args are substituted, but that's off-topic for this question), to allow raw texts (optionally with escape sentences) to be displayed in the console
If another data type is passed, it will be inspected (intended for debugging, the same way as util.inspect() does it), that is, it will be converted to a format nearly identical to the JS syntax that created it. That makes the strings inside complex data structures displayed as their representation: with quotes around them and special characters escaped.
Your strings contain NULL characters between each letter (that's probably because your code treats a UTF-16 string as UTF-8 or ASCII somewhere), which don't appear when logged to the console, but show up escaped (\x00) when the string is inspected.
That is the cause of the inconsistency between the two logging methods.
{ ssid: ssid, password: pwd }
It is a object not string.

SyntaxError: Unexpected token r in JSON at position 38

I was unexpected token r in JSON at position 38 for this code.
var object = JSON.parse('{"isFaceboook" : true,"redirectUrl" : redUrl,"facebookId" : id}');
redUrl and id are initialized and they are strings...
Your variables will need to be stringified as well before it can be parsed.
Something like: '{"isFacebook":true,"redirectUrl":"redUrl","facebookId":4}'
There's no point to making a JSON string and parsing it:
var object = {
isFacebook: true,
redirectUrl: redUrl,
facebookId: id
};
will work.

Unexpected token o in JSON at position 1

I keep getting this error in this block of code below:
function openWebsocket(url) {
var ws;
ws = $websocket(url);
ws.onOpen(function(event) {
console.log(' Websocket connection established:', event);
});
ws.onMessage(function(message) {
var userObj = UserFactory.getUserObject();
var settings = userObj.alert_settings;
// The JSON parsing...
var parsedMsg = JSON.parse(message.data);
var alert = JSON.parse(parsedMsg);
var date = new Date(parseFloat(alert.start_epoch+'000'));
alert.hour = date.getHours() +':'+date.getMinutes();
alert.percent_change = Math.round(alert.percent_change);
var shouldPush = main_alert_filter(settings, alert);
updateFeed(alerts, shouldPush, alert);
});
}
I've looked at both Parsing JSON giving "unexpected token o" error and I keep getting "Uncaught SyntaxError: Unexpected token o"
However neither answer helped. Because when I first run JSON.parse(message.data) I get a string back not an Object. So thus I have to run JSON.parse again to finally get a real object back.
This is what message.data looks like:
"
"{\"term\": \"\\\"nike\\\"\", \"percent_change\": 125, \"hour\": \"10:9\", \"term_id\": 2890413, \"start_epoch\": 1420474140, \"term_trend_id\": 793950, \"end_epoch\": 1420477740, \"formatted_date_difference\": \"January 5, 2015\", \"tickers\": [\"NKE\", \"$PUM\", \"ADDYY\", \"LULU\", \"UA\", \"HIBB\"], \"twitter_preview\": \"\", \"type\": \"spike\", \"approved\": 1, \"search_preview\": [\"\"]}"
"
Now after the first parsing parsedMsg is a string that looks like this:
{"term": "minimum wage +increase", "percent_change": 729, "hour": "9:14", "term_id": 2522115, "start_epoch": 1447168440, "term_trend_id": 657898, "end_epoch": 1447175700, "formatted_date_difference": "November 10, 2015", "tickers": ["$JAB", "$SLCY", "AAL", "AAPL", "ABCD", "ABTL", "ADDYY", "ADM", "AEO", "AFCO", "AHC"......
Finally I need an actual object, so I have to run JSON.parse again to get this:
Object {term: "minimum wage +increase", percent_change: 729, hour: "9:14", term_id: 2522115, start_epoch: 1447168440…}
Another thing to note, I never get that error when I'm stepping through in Chrome. It only happens when I don't have the breakpoint set. Could this be a race condition type issue? Like it tries to JSON.parse something that isn't ready to be parsed?
UPDATE
Ok so sometimes the JSON is invalid apparently and sometimes not, so far I'm doing good without errors with the following snippet, thoughts?
if (typeof alert === 'object') {
// do nothing...
} else {
var alert = JSON.parse(alert);
}
Most of the time the alert result of JSON.parse(message.data) is a string so I need the other check to double parse it.
Why would you parse your json second time, its already been parsed in the first attempt.
Have a look at the snippet
var obj = "{\"term\": \"minimum wage +increase\", \"percent_change\": 729, \"hour\": \"9:14\", \"term_id\": 2522115, \"start_epoch\": 1447168440, \"term_trend_id\": 657898, \"end_epoch\": 1447175700, \"formatted_date_difference\": \"November 10, 2015\", \"tickers\": [\"$JAB\", \"$SLCY\", \"AAL\", \"AAPL\", \"ABCD\", \"ABTL\", \"ADDYY\"]}";
$(function(){
var data = JSON.parse(obj);
alert(typeof data);
console.log(data.tickers[0] +" -> an item in `tickers` array");
console.log(data.tickers);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The JSON string you specified with message.data is not a well formed JSON parsed as String. It might be because the server is sending you a multi-part message during/after establishing the connection.
I suggest you print the message object received in OnMessage function and analyze if they are fully formed valid JSON Strings.
It looks like Your message.data is incomplete.
Take a look on the library docs You are using, maybe you should collect the data until it's end? Maybe there is some onEnd method?

Uncaught Error: INVALID_CHARACTER_ERR: DOM Exception 5

$('form#update').submit(function(){
var _data = $(this).serializeArray();
var param = {};
$.map(_data,function(a,b){
if(a.name=='HotelName'){
param[a.name] = window.btoa(a.value);
}
else{
param[a.name] = a.value;
}
});
console.log(param);
$.post('api.coupon_edit_post.php',param,function(r){
coupons();
reloadMarkers();
});
return false;
});
Is window.btoa causing this error?
I'm using window.btoa so I can pass most of the characters.
EDIT: I tried the MDN solution but it's not working. I am using Google Chrome Version 24.0.1312.57 m
The Error comes definitely from window.btoa.
You should modify the MDN solution and omit the decoding step before the conversion, like following:
function utf8_to_b64( str ) {
return window.btoa(encodeURIComponent( str ));
}
function b64_to_utf8( str ) {
return decodeURIComponent(window.atob( str ));
}
This creates the b64 string from the encoded string instead of decoding it again (which again would create symbols, btoa can't process). Now this works:
utf8_to_b64('✓ à la mode');
b64_to_utf8("JUUyJTlDJTkzJTIwJUMzJUEwJTIwbGElMjBtb2Rl");
of course due to the encoding this significantly lengthens the b64 string.
You can now modify your example:
param[a.name] = utf8_to_b64(a.value);

Categories