SyntaxError: Unexpected token r in JSON at position 38 - javascript

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.

Related

Unexpected token '&' while reading json object as string in javascript

I have a model which will read a json object as a string.
string zipCodes = "[{'zip': '06854','market_area': 'R01','state': 'CT'},
{'zip': '06842','market_area': 'R01','state': 'CT'},
{'zip': '02765','market_area': 'R02','state': 'TN'}]"
I am trying to read this string as a constant in javascript.
const array = #Model.zipCodes;
But the value is returning as
const array = [{'zip': '06854','market_area':
'R01','state': 'CT'},
{'zip': '06842','market_area':
'R01','state': 'CT'},
{'zip': '02765','market_area':
'R02','state': 'TN'}];
and throwing an unexpected token '&' error.
How can we handle this error.
Thank you.

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

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?

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

Error in Reading Json String with backslash in JavaScript

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.

Categories