I need to get an array from a json file and I have no idea how to do it.
Here's the code I want to get the array from:
$.getJSON('saveGames/userID' + userID + '_SAVEALPHA.json', function(data) {
console.log("Save data from: userID" + userID + "_SAVEALPHA.json: " + data);
var testVar = jQuery.parseJSON(data);
var pokemonAryTest = testVar[0].pokemon;
pokemonAry = [pokemonAryTest];
console.log("loaded players Pokemon: " + pokemonAry);
console.log(pokemonAry[0])
});
I have tried to change the index of pokemonAry to 1 and it returns undefined. And when I keep the index the same, it returns ["Pikachu, Charmander"] so I think its acting like as if it's a string.
Here's the .json:
"[{\"userID\":\"1\",\"saveName\":\"g\",\"pokemon\":[\"Pikachu, Charmander\"]}]"
When you are using getJSON() method no need to parse JSON data, jQuery take care of it. :)
$.getJSON('saveGames/userID' + userID + '_SAVEALPHA.json', function(data) {
console.log("Save data from: userID" + userID + "_SAVEALPHA.json: " + data);
var pokemonAry = data[0].pokemon;
console.log("loaded players Pokemon: " + pokemonAry);
console.log(pokemonAry[0])
});
Related
I've got a problem with JSON in JavaScipt. I've got 2 different JSON URL. One of them contains data about users and the second one about posts. And in posts JSON I've got a field userId.
I want to find a way to connect them somehow. I need to get users and their posts and then count how many posts every user wrote.
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users){
document.write("</br></br>"+ users[k].name +", " + users[k].username + ", " + users[k].email + "</br>" + "-------------------------------------------------------------------------------------" + "</br>");
for(k1 in posts){
if(posts[k1].userId===users[k].id){
document.write(posts[k1].body + "</br>");
}
}
}
};
userRequest.send();
};
postRequest.send();
but I think it doesn't look good. I want to get data from JSON to variable to use them later, in function for example.
Anyone help? I've never connected data from 2 JSON files and want to do it in a good way and getting good practice.
Use this instead
for(k in users){
for(k1 in posts){
if(posts[k1].userId===users[k].id){
if(!users[k].hasOwnProperty('posts')) {
users[k].posts = [];
}
users[k].posts.push(posts[k1].body);
}
}
}
if you could you jquery
$.when($.ajax({
url: "https://jsonplaceholder.typicode.com/users"
})).then(function(data, textStatus, jqXHR) {
$.each(data, function(index, value) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts?userId=" + value.id
}).then(function(data, textStatus, jqXHR) {
console.log("UserID:" + data[0].userId + " Nos Posts:" + data.length);
});
});
});
You can try above code and let me know if it solve your purpose
Steps you can use :
1. You can add a body property in to the objects in users array as per the id and userid match.
2. Later you can iterate the users array whenever you want to use.
DEMO
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users) {
for(k1 in posts) {
if(posts[k1].userId===users[k].id){
users[k].body = posts[k1].body;
}
}
}
console.log("users", users);
};
userRequest.send();
};
postRequest.send();
I'm stuck in a script here, not sure how to get it to print in the div I set up. I imagine it's something related to how I'm handling the response.
The response in chrome devtools looks like this:
{
"[\"record one\", \"/description\"]": 0
}
I've attempted to use both each and map to iterate the data out but so far not going anywhere. I'm brand new to js and jquery, so the script is mostly from reading and examples.
Maybe some kind of nested loop? Here is my code -
$(function() {
return $('#myslider').slider({
range: true,
min: 0,
max: 20,
values: [1, 20],
stop: function(event, ui) {
var max, min;
min = ui.values[0];
max = ui.values[1];
$('#range').text(min + ' - ' + max);
$.ajax({
url: '/dir_scan',
type: 'get',
data: {
min: min,
max: max
},
dataType: 'json',
success: function(response) {
var albums;
albums = response;
$.each(albums, function(index, obj) {
var albumname, artist, li_tag;
li_tag = '';
albumname = obj.AlbumName;
artist = obj.Artist;
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
}
});
}
});
});
As Will said in the comments, the JSON looks off.
But, you're on the right track of using .each, as it looks that you're returning an array of objects.
Here's an example of what to do:
var li_tag = '';
$.each(albums, function(index, obj) {
var albumname = obj.AlbumName;
var artist = obj.Artist
li_tag += '<li>Artist: ' + artist + ', Album: ' + albumname + '</li>';
$('#result').append($(li_tag));
return console.log;
});
Additionally, 'albums' should be set to the returned response of the success function. You're potentially creating a bunch of headache to try and decipher from the window.location; especially since the json example looks malformed. And, any work done with the data returned from the ajax call, should occur in the success function.
Here is how iteration worked for this situation. Comments in code -
success: function(response) {
var albums;
// side issue - but I had to clear the div to get a complete refresh
$('#result').empty();
albums = response;
$.each(albums, function(key, value) {
var albumname, li_tag, path;
li_tag = '';
// I found I had to do this parseJSON call otherwise
// I had no correct key/value pair, even though I had set dataType
// to JSON
albumname = jQuery.parseJSON(key);
path = albumname[1];
li_tag += '<li ><a href=/album' + encodeURI(albumname[1]) + '>' + albumname[0] + '</a href></li>';
$('#result').append($(li_tag));
return console.log;
});
Actually, value in the code is just the index number, but I had the actual key/value pair separated by commas, so again the parseJSON seemed to be the only way it would work. This, despite trying things like split and substr. Hope my answer is clear if not I can edit.
I am new to localstorage.I am trying to store json data in one file and retrieving the data in other file.Below is my json data which i have fetched from an url.I have tried storing feeds data using using localstorage now i am tring to fetch the data in other html file.But i am getting only the final object from the feeds.How can i get all the feed objects in other file.
{
"channel":{
"id":9,
"name":"my_house",
"description":"Netduino Plus connected to sensors around the house",
"latitude":"40.44",
"longitude":"-79.9965",
"field1":"Light",
"field2":"Outside Temperature",
"created_at":"2010-12-14T01:20:06Z",
"updated_at":"2017-02-13T09:09:31Z",
"last_entry_id":11664376
},
"feeds":[{
"created_at":"2017-02-13T09:07:16Z",
"entry_id":11664367,
"field1":"196",
"field2":"31.507430997876856"
},{
"created_at":"2017-02-13T09:07:31Z",
"entry_id":11664368,
"field1":"192",
"field2":"30.743099787685775"
},{
"created_at":"2017-02-13T09:07:46Z",
"entry_id":11664369,
"field1":"208",
"field2":"28.280254777070063"
}]}
One.html:-(here i am storing all the feeds data)
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
localStorage.setItem('Created_at', feed.created_at);
var create = localStorage.getItem('Created_at');
console.log(create);
localStorage.setItem('Entry_id', feed.entry_id);
var entry = localStorage.getItem('Entry_id');
console.log(entry);
localStorage.setItem('Field1', feed.field1);
var fd1 = localStorage.getItem('Field1');
console.log(fd1);
localStorage.setItem('Field2', feed.field2);
var fd2 = localStorage.getItem('Field2');
console.log(fd2);
});
other.html:(here i am trying to fetch the localstorage data)
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var create = localStorage.getItem('Created_at');
console.log(create);
document.writeln("<br>Created_at = "+create);
var entry = localStorage.getItem('Entry_id');
document.writeln("<br>Entry_id = "+entry);
var fd1 = localStorage.getItem('Field1');
document.writeln("<br>Field1 = "+fd1);
var fd2 = localStorage.getItem('Field2');
document.writeln("<br>Field2 = "+fd2);
}
</script>
Because you are over-riding the localStorage item in your for Loop.
The required for loop when simplified looks like:
json1.feeds.forEach(function(feed, i) {
localStorage.setItem('Created_at', feed.created_at); //Gets over-riden on every iteration
localStorage.setItem('Field1', feed.field1);});
That's why after the loop is completed. The Created_at field would only have the value of the most recently processed item in the array i.e. the last element. What you need to is create a corresponding array where each element would correspond to a feed item that you are reading from the API response.
Now, localStorage can simply store key value pairs. It doesn't have support for types like array. What you can do is something on these lines (Untested Code):
json1.feeds.forEach(function(feed, i) {
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
});
Yes, You will have to check if feedsArray key exists or not and set it as an empty array the first time. I have deliberately not put in the entire code as it is quite simple and should be good exercise for you.
So, once you are done and you want to read all the feeds from localStorage. Just get the feedsArray key and parse it and then iterate over it. Put simply, the basic idea is to have a JSON array of feeds and store it as a string with key feedsArray in localStorage.
The code snippet I have given above can get you started toward the solution I propose.
Relevant SO Post
The answer for the above issue is below.through which i got the solution.But not too sure if der is any wrong.
one.html:
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are :\nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]')
}
});
other.html:
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]');
//feedsArray.push(savedArr);
}
console.log(savedArr);
document.writeln("<br>FEEDS = "+savedArr);
}
</script
I have one ajax request which i use to extract data from API, and create a table from the extracted data. Now i need to do the same, but to extract the data from two different URLs and merge is to the same table (retTable).
Here is my current code (one ajax request):
$.ajax(
{
url : '/url/status',
type: "GET",
success:function(data, textStatus, jqXHR)
{
theRows = extract_status_data(data)
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error')
}
});
}
function extract_status_data(jsonDataRaw){
jsonResultSect = jsonDataRaw['result']
retTable = ""
for( key in jsonResultSect){
statusParam = jsonResultSect[key]
a = statusParam['a']
b = statusParam['b']
c = statusParam['c']
d = statusParam['d']
e = statusParam['e']
retTable += "<tr><td>" + dropDownList(key) + "</td><td>" + key + "</td><td>" + a + "</td><td>" + b + "</td><td>" + c + "</td><td>" + d + "</td><td>" + e + "</td></tr>"
}
return retTable
}
How would be correct to combine the data from two different URLs? Please advise.
I can't hammer out a really robust solution right now, but here is what I came up with: https://jsfiddle.net/heejse8h/
Basically the principal is that you place all the URLs in an array and keep a flag variable incrementing for every url you pull from. This might look like this:
urls = [
'/url/status',
'/url/status2'
];
var i = 0;
Then when you execute the AJAX, you'll want to store that in some array
var result = [];
For my AJAX call in the jsfiddle, I used this basic structure
$.ajax({
url : urls[i],
type: "GET",
success: function(data) {
// simplified example of storing the results
// the example code from the fiddle is more
// involved.
result[key].push(data);
if(urls[++i] !== undefined){
// if there is another URL, use the same
// ajax object (using `this`), extend it,
// changing only the URL, and call it.
// the important part is that the `this`
// object has a reference to the currently
// executing `success` method.
$.ajax($.extend(this, {url: urls[i]}));
} else {
// otherwise, we're at the end of our URLs
// and we can focus on final formatting and
// display of the data.
for( key in result ){
$('#mytable').append("<tr><td>" + dropDownList(key) + "</td><td>" + key + "</td>" + result[key].join('') + "</tr>");
}
}
}
});
In the end I would have liked to flesh this out and use the DOM API to actually create nodes rather than constant concatenation, but this solution already diverges from the original code quite a bit. You might want to consider creating a function that parses an object rather than relies on concatenation.
I'm trying to create a function which uses a combination of jquery, json and javascript to retrieve a twitter feed using the $.getJSON() method.
I have the function working with a static url like so:
$.getJSON("http://twitter.com/status/user_timeline/owzzz.json?count=1&callback=?", function(data) {
What I'm trying to do is replace where you see the username owzzz and count with values passed into the function.
the function looks something like this:
var twitterFeed = function(username, count){
$.getJSON("http://twitter.com/status/user_timeline/owzzz.json?count=1&callback=?", function(data) {
$.each(data, function(i) {
var timestamp = new Date(this.created_at);
var text = this.text;
$("#twitter").html(text +'<a href="http://twitter.com/' + username + '/" class="timestamp">' + username + ' <span>' + timestamp.toDateString() + '<\/span><\/div>' ).click(function(e) {
window.location = 'http://twitter.com/' + username;
e.preventDefault();
});
});
}); } twitterFeed('owzzz',1);
I can add the passed value username in the .html() but not inside the getJSON();
Any idea how I would go about this?
Do the same as you do in the html function: String concatenation.
$.getJSON("http://twitter.com/status/user_timeline/" + username + ".json?count=" + count + "&callback=?", ...)
string concatenation.
$.getJSON(
'http://twitter.com/status/user_timeline/' + username + '.json' +
'?count=' + count + '&callback=?'
);