Unexpected token o in JSON at position 1 - javascript

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?

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

Is there a way to pass a String array containing dates from server side to client?

I am trying to pass a String array from server side to client using Nodejs and Pug, but continuously get errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal"
The server is running v10.15.0 with PUG v2.0.3. I have tried encapsulating each element of the array in quotes. Tried a few different approaches with JSON, but keep getting the same errors. With the code below when I print the array in the console I get (only 4 elements, rest removed here for shortness):
[ '"2017-04-01T02:43:39.000Z"',
'"2017-04-01T06:37:05.000Z"',
'"2017-04-01T10:30:22.000Z"',
'"2017-04-01T14:23:41.000Z"',...]
I am literally lost at this time, can you please help?
//Server side
client.execute(query,[], function(err, result){
if(err){
res.status(404).send({msg: err});
} else {
for (i in result.rows){
currentDate = new Date(result.rows[i].event_time);
dates.push('"'+ currentDate.toJSON()+'"');
//dates.push(currentDate.toJSON());
}
if (result.rows[0] != null) {
res.render(page, {
datesA: dates,
//datesA: JSON.stringify(dates),
});
else {
res.status(404).send({msg: err});
}
}
});
//PUG
var dates =JSON.parse(#{datesA});
//var dates = JSON.parse(#{datesA});
//var dates = JSON.parse(JSON.stringify(#{datesA});
//var dates = #{datesA};
Try this in pug file (in script section):
var dates = !{JSON.stringify(datesA)};

JSON Parse not working, parsing two dimensional array

I am trying to parse this LOCAL XMLhttprequest, I am getting back the right response text and displaying it in safari.
When I make an object to JSON.parse() the responsetext,I am getting errors like "unidentified token '"' " or "expected '}' " no matter how I change the .txt file, it will not parse into an object for me
I have tried to change the .txt to the right JSON format with no luck
{playerGrid: [["3","2","2","2","2","2","2","3","3","3"], ["3","2","2","2","2","2","2","2","2","2"], ["3","2","2","2","2","2","2","2","2","3"],["3","2","2","2","2","2","2","2","2","3"], ["4","2","2","2","2","3","2","2","2","3"], ["2","2","2","2","7","3","2","2","2","3"], ["2","2","2","2","7","2","2","2","2","2"], ["2","2","2","3","3","3","2","2","2","2"], ["2","2","2,"2","2","2","2","2","2","2"], ["2","2","2","2","2","2","2","2","2","2"]],
computerGrid: [["2","2","2","7","4","9","9","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","9","9","2","2,"2","2"], ["2","2","2","2","2","2","2","2","2","2"], ["9","9","9","9","9","2","2","2","2","2"], ["2","2","2","2","7","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"]]};
here is my JOSN .txt
function fileRequest()
{
var localRequest = new XMLHttpRequest();
localRequest.open("GET", "sampleJSON.txt", false);
localRequest.send(null);
document.getElementById("jsonDiv").innerHTML = localRequest.responseText;
var jsonObject = JSON.parse(localRequest.response);
document.getElementById("jsonParsed").innerHTML = jsonObject.computerGrid;
}
here is my simple function, I first display the response, and then it errors when I am trying to parse the data.
Thanks
I expect an object that I can .computerGrid or .playerGrid.
You have some errors in your json, just search by "2,, there are 2 occurences, it should be "2",.
You are missing a closing ".
Also, in order to the JSON to be valid, it should look like this:
{"playerGrid":[["3","2","2","2","2","2","2","3","3","3"],["3","2","2","2","2","2","2","2","2","2"],["3","2","2","2","2","2","2","2","2","3"],["3","2","2","2","2","2","2","2","2","3"],["4","2","2","2","2","3","2","2","2","3"],["2","2","2","2","7","3","2","2","2","3"],["2","2","2","2","7","2","2","2","2","2"],["2","2","2","3","3","3","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"]],"computerGrid":[["2","2","2","7","4","9","9","2","2","2"],["2","9","2","2","2","2","2","2","2","2"],["2","9","2","2","2","2","2","2","2","2"],["2","9","2","2","9","9","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"],["9","9","9","9","9","2","2","2","2","2"],["2","2","2","2","7","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"]]}
Keys, playerGrid and computerGrid must be between ".
Use JSON.parse(localRequest.responseText)
Your JSON is incorrect, you are missing quotes around some numbers like "2,
Object Keys "playerGrid" and "computerGrid" must be quoted too
let d = `{
"playerGrid": [
["3","2","2","2","2","2","2","3","3","3"], ["3","2","2","2","2","2","2","2","2","2"],
["3","2","2","2","2","2","2","2","2","3"], ["3","2","2","2","2","2","2","2","2","3"],
["4","2","2","2","2","3","2","2","2","3"], ["2","2","2","2","7","3","2","2","2","3"],
["2","2","2","2","7","2","2","2","2","2"], ["2","2","2","3","3","3","2","2","2","2"],
["2","2","2","2","2","2","2","2","2","2"], ["2","2","2","2","2","2","2","2","2","2"]],
"computerGrid": [
["2","2","2","7","4","9","9","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"],
["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","9","9","2","2","2","2"],
["2","2","2","2","2","2","2","2","2","2"], ["9","9","9","9","9","2","2","2","2","2"],
["2","2","2","2","7","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"],
["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"]]
}`;
console.log(JSON.parse(d))
PS: you can always validate your json with codebeautify.org/jsonvalidator

Using JS to connect to an API and then output the JSON response

I'm trying to do a UK Postcode validation using JS by connecting to http://postcodes.io/ post code validation service.
When I post to api.postcodes.io/postcodes/POSTCODEVARIABLE/validate I should recieve a 200 response and result of either "True" or "False" depending on whether the postcode is valid or not.
However, when I try to receive the data (in JSON format) I get an error in the console:
"Uncaught SyntaxError: Unexpected token o in JSON at position 1"
Here is my code, if anyone could point out where I am going wrong, that would be great.
var cpostcode = 'RG1 8BT';
var cpostcode = cpostcode.replace(/\s+/g, '');
var myNewURL = 'https://api.postcodes.io/postcodes/' + cpostcode + '/validate';
var pcapi = new XMLHttpRequest();
pcapi.onreadystatechange = function() {
if (pcapi.readyState == XMLHttpRequest.DONE) {
alert(pcapi.responseText);
}
}
pcapi.open("GET", myNewURL, true);
pcapi.send(null);
var xyz = JSON.parse(pcapi);
console.log(xyz);
Like at #Youssef said you want to log the .responseText. You get that script error because pcapi is a XMLHttpRequest object and not valid json which JSON.parse() attempts to parse. If you want to learn more about what you can do with the pcapi object just console.log(pcapi) and you can see its {keys:values} or just read up on it.
JSON.parse() converts any JSON String passed into the function, to a JSON Object.
There is really no such thing as a "JSON Object". The JSON spec is a syntax for encoding data as a string. ... JSON is a subset of the object literal notation of JavaScript. In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around. - stackoverflow
var cpostcode = 'RG1 8BT';
var cpostcode = cpostcode.replace(/\s+/g, '');
var pcapi = new XMLHttpRequest();
var myNewURL = 'https://api.postcodes.io/postcodes/' + cpostcode + '/validate';
pcapi.open("GET", myNewURL, false);
pcapi.send();
var xyz = JSON.parse(pcapi.responseText);
console.log(xyz);

How to JSON parse in windows 8

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

Categories