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
Related
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
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);
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?
Is there any way I can check the response size? Data property is a byte array which I am using to display an image. If the size is greater than 10 MB I need to show a popup.
{
"Name": "sharon",
"Date": "07\/14\/2004",
"Data": "JVBERi0xLjINCg0KNC",
"DocumentId":1540,
}
Also how can I check the type of my response, whether it's blob or something? Can I check the size of the blob I am getting? Maybe something like this:
var data = JSON.parse(this.responseData);
You simply can use JavaScript .length for this, but do realize different browsers as well as servers will report different values since some interpretation of newlines can be 1 of 2 size values (byte-order).
Having said that, use a "loose" value that your sure contains the data you need, and not just the header response that has no value.
You can slurp the incoming response into one line and remove all unnecessary white-space.
var JSON = '{\r\n' +
' "Name": "sharon",\r\n' +
' "Date": "07\/14\/2004",\r\n' +
' "Data": "JVBERi0xLjINCg0KNC",\r\n' +
' "DocumentId":1540,\r\n' +
'}';
alert(JSON);
alert(JSON.length); // 101
var newJSON = slurp(JSON);
alert(newJSON);
alert(newJSON.length); // 91
function slurp(str) {
str = str.replace(/(\r\n|\n|\r)/gm,"");
str = str.replace(/(\s+|\t)/gm,' ');
return str;
}
I have Converted a C# class in Json Object after it I stringify that json Object then it converts with backslash(escaping character) and when i used following code to read the json string it gives me undefined message in alert .
<script>
var jsString = { "JsonString": ["{\"reachoutid\":1,\"user_ID\":1,\"question\":\"Best CMS in Microsoft .Net\",\"anonymous\":false,\"shared\":false,\"create_date\":\"\\/Date(-62135596800000)\\/\",\"update_date\":\"\\/Date(1327300086183)\\/\",\"status\":0,\"start_date\":\"\\/Date(-62135596800000)\\/\",\"end_Date\":\"\\/Date(-62135596800000)\\/\",\"reachoutfactorsList\":null,\"reachoutchoicesList\":[{\"reachoutid\":0,\"choice_ID\":4,\"orders\":0,\"description\":\"Sitecore\",\"preachOutID\":0,\"pchoice_ID\":4,\"porders\":0,\"pdescription\":\"Sitecore\"},{\"reachoutid\":0,\"choice_ID\":5,\"orders\":0,\"description\":\".Net Nuke \",\"preachOutID\":0,\"pchoice_ID\":5,\"porders\":0,\"pdescription\":\".Net Nuke \"},{\"reachoutid\":0,\"choice_ID\":6,\"orders\":0,\"description\":\"Drupal\",\"preachOutID\":0,\"pchoice_ID\":6,\"porders\":0,\"pdescription\":\"Drupal\"}],\"detail\":\"Write more text to check progress bar work properly.\",\"set_Listof_Tags\":null,\"tag\":null,\"get_Listof_Tags\":null,\"userstatus\":null,\"actType\":\"RO\"}"], "_getList_MyActivities": null, "_getList_MyPeersActivities": null, "userID": 1 }
for (i = 0; jsString.JsonString.length > i; i++)
{
alert(jsString.JsonString[i].reachoutid);
//"Giving Undefined Message "
}
</script>
Your JSON is stored as a string, not as a native object. To convert it back, change your alert( ... ) line to use JSON.parse( ... ) like this:
alert( JSON.parse(jsString.JsonString[i]).reachoutid )
Your JSON shouldn't be quoted. When it is, JS interprets is as a string instead of an object
var jsObject = { "JsonString": [{"reachoutid":1,"user_ID":1,"question":"Best CMS in Microsoft .Net","anonymous":false,"shared":false}]} // etc.