Strip out while(1) prepended to JSON object - javascript

I am making an ajax get request, but receive back a JSON object prepended with while(1) eg.
while(1);{"servers":[{"some_data": data, "etc":...}]}
We just started doing this to prevent malicious attacks, but I am not sure how to strip it out so that I can parse the JSON properly.
here is the function I am using for the $.get call
function myFunction() {
$.get('/v1/servers').success(function(data) {
data.servers.forEach(function(server){
presentServer(server);
});
});
}

Try this:
var text = ajaxResponse.responseText;
var jsonObject = JSON.parse(text.replace('while(1);', ''));
Another way without using replace:
var jsonObject = JSON.parse(text.substring(text.indexOf(';') + 1);
Updated with your function:
function myFunction() {
$.get('/v1/servers').success(function(response) {
var data = JSON.parse(response.responseText.substring(text.indexOf(';') + 1));
data.servers.forEach(function(server){
presentServer(server);
});
});
}

This is a standard XSS protection feature. Since you have tagged the question with jQuery, you should be able to do this:
$.get('/your/api.json', function (resp) {
var json = resp.substring(resp.indexOf(";")+1)),
data = $.parseJSON(json);
// do other things
});
with the code that you have posted above:
function myFunction() {
$.get('/v1/servers').success(function(resp) {
var json = resp.substring(resp.indexOf(";")+1)),
data = $.parseJSON(json);
data.servers.forEach(function(server){
presentServer(server);
});
});
}

You can use substring to strip your leading characters:
JSON.stringify(response);
response.substring(9,response.length);

Related

Use the data from 1st JSON and convert it to a variable and use that variable to call a 2nd JSON

I am new here but I have a problem and need your help, so in my code I called a JSON file.
var data = {};
var spectator;
var tmp = [];
var IDcatcher =[];
var summonerID = [];
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
});
so this gives me the ID from the JSON which is stored in summonerID variable now I want to use this variable to complete the URL to get the 2nd JSON so.
var spectatorUrl = "link" + summonerID;
Now get the 2nd JSON
var Charcatcher =[];
var CharID = [];
$.getJSON(spectatorUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (Charcatcher in tmp) {}
});
CharID = tmp[Charcatcher].id;
});
My problem is the 2nd JSON doesn't run, it doesn't get anything and returns nothing (obviously).
Help?
I can't run 2 JSONs at different times? If so how can I do it or change it?
As I mentioned, due to the asynchronous nature of JavaScript, if you have an AJAX request with a callback and some code following the request, JS will fire off the AJAX request and will continue with the rest of the code. It won't wait for the result of the AJAX request to return.
Here's a simple demo -
function first() {
setTimeout(() => {
console.log("1");
}, 2000);
console.log("2");
};
first();
Look at the order of the console.log statements in the code, and then check the actual order in the console.
To solve your original problem, you can nest a $.getJSON() inside the first one, this will ensure that summonerID is available when you fire off the second AJAX request.
$.getJSON(getUrl, function(data) {
tmp = data;
$.each(tmp, function(key){
for (IDcatcher in tmp) {}
});
summonerID = tmp[IDcatcher].id;
// second AJAX request
var spectatorUrl = "link" + summonerID;
$.getJSON(spectatorUrl, function(data) {
// logic
});
});

Javascript parse json from URL

Trying to parse a json response from URL in javascript.
Here is what the response looks like
{"data":[{"version":"7.4.0","startDate":"2016-12- 12","totalSessions":"6208723","totalCrashes":"2944","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-11","totalSessions":"4979676","totalCrashes":"2378","crashRate":"0.048"},{"version":"7.4.0","startDate":"2016-12-10","totalSessions":"534913","totalCrashes":"208","crashRate":"0.039"},{"version":"7.4.0","startDate":"2016-12-09","totalSessions":"309564","totalCrashes":"147","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-08","totalSessions":"255597","totalCrashes":"162","crashRate":"0.063"},{"version":"7.4.0","startDate":"2016-12-07","totalSessions":"21379","totalCrashes":"12","crashRate":"0.056"}]}
I can dump the json output using
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$('#show-list').html(data2); //shows json
});
Then I tried to parse it using
document.getElementById("placeholder").innerHTML=data2.data[0].version
also tried
obj = JSON.parse(crash);
console.log(obj.data2[0].version);
But no luck.
You should tell jQuery that the AJAX function returns JSON, then it will parse it automatically for you.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$("#placeholder").text(data2.data[0].version);
}, 'json');
Or you can call JSON.parse() yourself.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
var data = JSON.parse(data2);
$("#placeholder").text(data.data[0].version);
});

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

fetch json object containing 3 arrays with ajax call and pass arrays to javascript

I have a page that creates the following output:
<script>
var JSONObject = { "groups":['1210103','1210103','1210103','1210405'],
"prices":['279,00','399,00','628,00','129,00'],
"titles":['','','','']
};
</script>
This page is called by an ajax call:
$.ajax({url:plink,success: function(result) { }
I now need to recieve the json arrays and pass them to ordinary javascript arrays.
How do I do that?
I have tried with:
result = jQuery.parseJSON(data);
mygroups = result.groups;
myprices = result.prices;
mylabels = result.titles;
Change your page so that it just produces JSON:
{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}
Note that in JSON, you must use ", not ', for quoting strings.
Have it return a Content-Type header of application/json. If for some reason you can't set the correct Content-Type header on the response, you can force jQuery to treat the response as JSON by adding dataType: 'json' to your ajax call, but it's best to use the correct content-Type.
Then in your ajax call's success callback, result will already be a deserialized object with three properties (groups, prices, titles), which will be JavaScript arrays you can work with.
Live Example | Source
You've said in the comments below that the page is a full HTML page with the embedded script tag and you have no control over it other than the contents of the script tag, because of the CMS you're using.
I strongly suggest moving to a more flexible CMS.
Until/unless you can do that, you can simply receive the page as text and then extract the JSON. Change your script tag to something like this:
<script>
var JSONObject = /*XXX_JSONSTART_XXX*/{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}/*XXX_JSONEND_XXX*/;
</script>
Note the markers. Then you can extract the JSON between the markers, and use $.parseJSON on it. Example:
(function($) {
$.ajax({
url: "http://jsbin.com/ecolok/1",
dataType: "text",
success: function(result) {
var startMarker = "/*XXX_JSONSTART_XXX*/";
var endMarker = "/*XXX_JSONEND_XXX*/";
var start, end;
start = result.indexOf(startMarker);
if (start === -1) {
display("Start marker missing");
}
else {
start += startMarker.length;
end = result.indexOf(endMarker, start);
if (end === -1) {
display("End marker missing");
}
else {
result = $.parseJSON(result.substring(start, end));
display("result.groups.length = " + result.groups.length);
display("result.prices.length = " + result.prices.length);
display("result.titles.length = " + result.titles.length);
}
}
}
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
Live Copy | Source

JSON parse issue

I have a JSON string like this:
{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}
How can I parse this using javascript? I have tried using:
function callbackFun(data) {
$j.each(data.result, function(i, item) {
alert(this.time);
});
}
But it seems this is not correct.
If you retrieve that piece of data from $.ajax() then you could set up dataType: 'json' to get it automatically parsed for you.
Otherwise just use $.parseJSON()
If you're using jQuery, it's trivial:
var obj = '{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}';
var json = jQuery.parseJSON(obj);
alert(json.time);
alert(json.countryName);
http://api.jquery.com/jQuery.parseJSON/
Are you looking for this?
var MyJson = '{"time":"2011-11-30 04:44","countryName":"Austria","sunset":"2011-11-30 16:32","rawOffset":1,"dstOffset":2,"countryCode":"AT","gmtOffset":1,"lng":10.2,"sunrise":"2011-11-30 07:42","timezoneId":"Europe/Vienna","lat":47.01}';
var MyObject = jQuery.parseJSON(MyJson);

Categories

Resources