i have a json file in an url that appears like this
[{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank":"II","veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false},
{"tier":"BRONZE","leagueName":"Kennen's Adventurers","queueType":"RANKED_FLEX_SR","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":2,"wins":28,"losses":41,"rank":"III","veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}]7
I want to parse it, either through javascript and use it to display the tier, rank and leaguepoints in html.
I'm new at this, and I cant figure out how to parse the json into usable variables to display in the html file. please help if u can.
You can use jquery to get the json from url
$.getJSON('http://myurl', function(data) {
for(var i = 0, len = data.length; i < len; i++) {
var obj = data[i];
//obj will be your item with obj.tier, obj.leagueName etc.
}
});
Refer to the question How to get JSON from URL in Javascript for accessing the data from the URL. Then you can iterate through the data with a loop:
var data = [{"tier":"SILVER","leagueName":"Tryndamere's Wizards","queueType":"RANKED_SOLO_5x5","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":18,"wins":411,"losses":430,"rank":"II","veteran":true,"inactive":false,"freshBlood":false,"hotStreak":false}, {"tier":"BRONZE","leagueName":"Kennen's Adventurers","queueType":"RANKED_FLEX_SR","playerOrTeamId":"91248124", "playerOrTeamName":"NunoC99","leaguePoints":2,"wins":28,"losses":41,"rank":"III","veteran":false,"inactive":false,"freshBlood":false,"hotStreak":false}]
for (var i = 0; i < data.length; i++) {
// Within the loop you can access each field of each object
// as shown below
// data[i].tier
// data[i].leagueName
// data[i].queueType
// data[i].playerOrTeamId
// data[i].leaguePoints
// data[i].wins
// data[i].losses
// data[i].rank
// data[i].veteran
// data[i].freshBlood
// data[i].hotStreak
// data[i].inactive
}
You can use methods like document.createElement("TAG_NAME") and document.appendChild(childElement) to insert the data into an HTML document.
Related
I have to make a call to a json that varies according to the id that I pass in the url, for this I must go through an array of identifiers and modify the url of the json inside the loop. But unfortunately it doesn't go inside the json function until the loop iterations have finished.
var IdList = ['1401', '5724', '5802', '3502', '2101'];
for(l = 0; l < IdList.length; l++){
$.getJSON('https://www.urljson.com?id='+IdList[l]+'', function(emp) {
price = emp.data.price;
currency = emp.data.currency;
});
}
Could someone tell me what is happening?
Thanks!
I need some help with Javascript. I have some data that I received from youtube APIs. The data is retrieved from the below URL's (I only showed 2 but I get from multiple other channels too)
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCpVm7bg6pXKo1Pr6k5kxG9A
https://www.googleapis.com/youtube/v3/search?key=AIzaSyDuS9LWv86VFCFr4ZD_Kwp5--Zi6YKo_rM&part=snippet,id&order=date&maxResults=50&channelId=UCLQZTXj_AnL7fDC8sLrTGMw
Every item in these json files has "publishedAt" value. Now I want to merge the data from both the JSON files and sort the list based on the "publishedAt" key i.e., the latest uploaded videos shown first.
Here is what I have currently which works perfectly for one file (I didn't do any magic, the URL itself sorts the items based on date)
$.getJSON(sourceUrl, function (data) {
//console.log(data);
//var you_data = JSON.stringify(data);
var videosCount = data.items.length;
console.log("The number of videos is: " + videosCount);
for ( i = 0 ; i < videosCount; i++) {
var title = data.items[i].snippet.title;
var url = "https://www.youtube.com/watch?v=" + data.items[0].id.videoId;
$("#reply").append(" " + title + "<br><br><br>");
//console.log(title);
//console.log(url);
};
});
How do I get this done?
EDITED (my thoughts):
Something that I can think of is using nested objects. I can create a new object that two looks something like:
grand_parent_object = { {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}, {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item2 as shown in the JSON file}}, etc}
here the parent_object is {'publishedAt':xxxxxxxx, 'wholeItem':{the whole item as shown in the JSON file}}
Maybe I should sort the parent_objects based on their 'publishedAt' values first and then that should do the job???? PS: 'publishedAt' in parent_object is the same as 'publishedAt' in the 'wholeItem' value.
Solution:
I used Ross's logic and it worked. I had issues with .getJson since it wouldn't update the global variable, wholearray. So I used .ajax and it worked. Here is my working code:
function getAjaxData(sourceUrl) {
$.ajax({
async:false,
url:sourceUrl,
success: function(data) {
var videosCount = data.items.length;
for ( var i = 0 ; i < videosCount; i++) {
var tempobject = {};
tempobject.published = data.items[i].snippet.publishedAt;
tempobject.wholeItem = data.items[i];
wholearray.push(tempobject);
}
}
});
}
One solution is to create a new array of object literals, then sort the array based on the key:
var array = [];
$.getJSON(url, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
$.getJSON(otherUrl, function(data){
for (var i=0; i<data.length; i++){
var object = {}
object.published = data.items[i].snippet.publishedAt
object.wholeItem = data.items[i]
array.push(object);
}
})
Have a listener that waits for both AJAX calls to finish, then you can sort:
array.sort(function(a,b) { return a.published - b.published; });
This question gives more info on sorting
This may not be the most efficient way, but it's the first that comes to mind and will work swell!
I have a json object that i created using obj = JSON.parse(data). "data" was recieved from a webserver. I know the object is correct because i can print single variables from it into a div or my list.
This is what is the json object is created from:
[{"name":"Staurikosaurus","group":"Saurischia","diet":"Carnivore","period":"Triassic"},{"name":"Diplodocus","group":"Saurischia","diet":"Herbivore","period":"Jurassic"},{"name":"Stegosaurus","group":"Ornithischia","diet":"Herbivore","period":"Jurassic"},{"name":"Tyrannosaurus","group":"Saurischia","diet":"Carnivore","period":"Cretaceous"}]
Literally all i want to do is put this into a to show up on a web page.
My current code:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
$('#myList').html("<li>"+obj[0].period+"</li><li>"+obj[2].period+"</li>");
//$('#myList').html("<li>obj[2].period</li>");
});
}
This successfully prints out the list with Triassic then Jurrasic.
I would prefer to do this in Jquery but javascript is okay.
Thank You.
You are not iterating through the list, just printing out the 0-th and 2nd element in the array. Try:
function getJson(){$.get(MY URL, function(data) {
// String
//console.dir(data);
// Parse JSON
var obj = JSON.parse(data);
// JSON object
//console.dir(obj);
var inner = '';
for(i=0; i < obj.length; i++) {
inner += "<li>"+obj[i].period+"</li>";
}
$('#myList').html(inner);
});
}
I'm sure there's a cleaner way using jQuery but that should work
If you're want to use the jQuery syntax, process like this:
var listElement = '';
$.each(obj, function(index, value) {
listElement += '<li>' + data[obj].period + '</li>';
})
$('#myList').html(listElement);
{"0":
{"id":"276","course":"92","name":"Tutorial - Compound Measures",
"activitylink":"2490","available":"1331231400","deadline":"1331235000"},
"1":
"example#gmail.com","reference":"example#gmail.com"}
I am trying to access this in jQuery/Javascript but I unable to. This is my jQuery:
$('#lessonSelect').live('change', function()
{
$.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data)
{
var len = data.length;
var lessonDialog = "";//initialise
var launchLessonDiv = 'Launch Lesson';
for (var i = 0; i< len; i++)
{
lessonDialog += '<p>' + data[i].name + '</p>'; //get lesson name
}
$('#lessonDialog').html(lessonDialog); //insert lesson name into dialog
$('#launchLessonDiv').html(launchLessonDiv);
});
});
This is basically for a select list. Each time the user selects something, links and other stuff on the page change. The stuff works when the page is first loaded but when I start selecting stuff in the select list the lessonDialog comes up blank with nothing inside it.
Convert the object with numeric keys to a true array:
$.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data) {
data = Array.prototype.slice.call(data);
Your current method fails, because { ... } results in the creation of an object, not an array. The length property of the object is undefined, so the loop would never get started:
for (var i=0; i<undefined; i++) ; // <-- 0 < undefined is always false
Im trying to pull a specific file name from a URL, Ive looked at the posts but there isnt anything that answers the question that I need. I need a Javascript or Jquery that can pull just the file name ("Test1") from:
http://sharepoint/sites/Jarrod/DurangoTest/SitePages/Home.aspx?RootFolder=%2Fsites%2FJarrod%2FDurangoTest%2FShared%20Documents%2FTest1&FolderCTID=0x01200094D5A58A4F099E49BE1A8BA2F7DE9E0D&View={653454F3-1CE4-48C1-967C-5BA6023D349E}
You can get url information like that from the window.location object. Try this out
params = window.location.search.split(/&/)
for (var i=0; i < params.length; i++) {
if (params[i].match(/^\??RootFolder=/)){
paths = params[i].split(/\//);
filename = paths[paths.length-1];
break;
}
};
#Jonathan is on the right track. It looks like you're looking to parse a value from the querystring rather than find the name of the requested file. You'll first need to get the value from the querystring. You can use window.location.search to get the full querystring from the URL. Then parse the querystring to find the value you want. Here's a little JS function that does that:
// parses the query string provided and returns the value
function GetQueryVariable(query, name) {
if (query.indexOf("?") == 0) { query = query.substr(1); }
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return "";
}
Then you're ready to parse the value using Jonathan's suggestion to get the name of the file. You might have to do some unescaping (using the JS method unescape) to convert the value from the querystring into the "real" value that can be parsed more easily.