Iterate through JSON to retrieve single variable - javascript

I have a JSON local file that looks like:
{
"sites" : [
{
"name" : "Somename",
"url" : "https://url.com",
"api" : "http://url.com/api",
},
{
"name" : "Somename2",
"url" : "https://url2.com",
"api" : "http://url2.com/api",
}
}
Each api has a single integer data that I need to store in the database. How do I iterate such JSON in Javascript? As soon, as I'm able to retrieve that api url I will be able to write another function and get the integer i want. What I've tried was:
function getNetworkData(){
$.getJSON('../json/sites/site-list.json', function(data) {
var sites = JSON.parse(data);
sites.forEach(function(data){
console.log(data.sites[0].name)
});
});
}
...but that just doesn't work. I keep getting an error:
Unexpected token o in JSON at position 1

The function $.getJSON already parses the response from the server/source.
So, you don't need to parse it using JSON.parse, further, you're trying to loop using the array as follow:
sites.forEach
What you really want is loop the attribute sites:
data.sites.forEach(function(s){
console.log(s.name);
});

You already got JSON, there is no need to parse. Refer jQuery.getJSON
Update from
var sites = JSON.parse(data);
sites.forEach(function(data){
console.log(data.sites[0].name)
});
to
data.sites.forEach(function(site){
console.log(site.name); // prints name
console.log(site.api); // prints api
});

Like this:
function getNetworkData(){
$.getJSON('../json/sites/site-list.json', function(data) {
data.sites.forEach(function(site){
console.log(site.name)
});
});
}
The object you are looping through doesn't need the index.
site is already equal to sites[0] on the first loop, sites[1] on the second loop etc, so you just need site.name

Skip JSON.parse(data); You will get an object with $.getJSON() that you can manipulate. See getJson

Related

NodeJS not able to process array of objects received via POST

I'm having this collection of objects which are inside a html text area:
{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...
...
Is there a way to send the whole collection to node js and iterate through it to get values of objects?
My AJAX code:
$.ajax({
type: "POST",
url: "https://example.com/nodeapp",
data: '['+document.getElementById("list").value+']',
success: function(data) {
console.log(data);
}
});
I tried to do a foreach on req.body, but it doesn't seem to work:
var arr = req.body;
arr.foreach(element=>{
console.log(element.email);
})
Gives the error:
TypeError: arr.foreach is not a function
At first , you have to parse the body by using JSON.parse() function .
Like this :
var arr = JSON.parse(req.body);
arr.forEach(element=>{
console.log(element.email);
});
The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .
I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:
'[{"name":"John", "lname":"Doe","company":"example company","email":"johndoe#example.com"},
{"name":"Katie","lname":"Jake","company":"example company","email":"katie#example.com"},
...
...]'
Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:
{
"<<the array in string format>>" : ""
}
How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)

How can I assign a key to an array of values to pass to an API?

Im using Angular with pure JS. I have an array like this:
arr = [1, 2, 5, 32];
But I need to POST this to an API in JSON. I'm trying to achieve this:
{'reportIDs': [1, 2, 5, 32]}
Is there an easy way to do this in Angular?
Wherever it is that you need this value, you can create that object almost exactly as in your question:
var obj = {'reportIDs': arr};
You don't need the ', but they don't do any harm.
But if you really need to send JSON, your example isn't JSON. In JSON, property names must be in double quotes. The simplest way to create valid JSON is to use JSON.stringify:
var json = JSON.stringify({reportIDs:arr});
If you're sending that somewhere, you'd use that value as the data in a $http call.
You might want to use angular.toJson instead of using JSON.stringify directly, as it skips some internal Angular prooperties.
You need to sent an Ajax request to the server
If you want to keep the json code, insert it as a string
$http.post("the_url_to_sent_data",
{'json' : JSON.stringify({'reportIDs': arr})}
).then(function (response) {
// Hey, i got a responce
return response;
});
Then get the json parameter's value and parse it.
Or just send the data and let the library parse them
$http.post("the_url_to_sent_data",
{'reportIDs': arr}
).then(function (response) {
// Hey, i got a responce
return response;
});

how could I can I read an array I save in a cookie with jquery.cookie?

I am using jquery.cookie (https://github.com/carhartl/jquery-cookie/tree/v1.4.1) and Ive been having many problems with this, I am trying to save an array of this structure
var obj = {
'row1' : {
'key1' : 'input1',
'key2' : 'inpu2'
},
'row2' : {
'key3' : 'input3',
'key4' : 'input4'
}
};
But when I want to read it I get this
row1%5Bkey1%5D=input1&row1%5Bkey2%5D=inpu2&row2%5Bkey3%5D=input3&row2%5Bkey4%5D=input4
I am sending it at this way:
$.cookie('listresult', $.param(obj), { expires: 10 });
The worst is that sometimes works, and sometimes doesnt, so, I have no idea whats wrong... Any idea how to send and transform the data?
To read it I use this
var cookieValue = $.cookie("listresult");
When I try this... doesnt work
$.parseJSON($.cookie("listresult");)
Thanks
You shouldn't use jquery.param method. It is intended for use with HTTP (AJAX) requests so that's not your case. You have to use JSON.stringify on writing cookie and JSON.parse on reading:
// write (save):
$.cookie('listresult', JSON.stringify(obj), { expires: 10 });
// read (restore):
var obj = JSON.parse($.cookie('listresult'));
If you carefully read jQuery plugin's manual, you'll find this:
json
Turn on automatic storage of JSON objects passed as the cookie value.
Assumes JSON.stringify and JSON.parse:
$.cookie.json = true;
This way your JavaScript objects will be serialized to JSON when you set the whole cookie, and they'll get deserialized into a JavaScript again when you retrieve that cookie.

Trying to pull data from parse and render with underscore.js getting empty frields

Trying to pull data from parse.com and use underscore.js I tried using this to build a table of the data. When I run it with hard coded json it works but when I try running it with pulled data returns an empty table.
Parse.initialize("", "");
var allDeals = Parse.Object.extend("Deal");
var query = new Parse.Query(allDeals);
query.find({
success: function(results){
var deals = JSON.stringify(results);
var template = $("#usageList").html();
$("#target").html(_.template(template,{deals:deals}));
},
error: function(error) {
alert('something was wrong');
}
});
Thanks in advance!
Like #mu said it would be easier to see whats in results..
But I have run into this with Parse before. Taking a guess.. You can try this
$('#target').html(_.template(template, { deals: results.models }));
"results" is a backbone collection and "models" holds the array of objects you are after.
Presumably you're getting a JavaScript object of some sort in results in your success callback. Then you serialize that to a JSON string with:
var deals = JSON.stringify(results);
That leaves you with a string in deals and your template probably doesn't know what to do with a string, it probably wants an object or whatever was in results in the first place. Try skipping the stringification and just feed results straight into the template:
$('#target').html(_.template(template, { deals: results }));

getJSON() - how to remove AND-sign in front of data param?

I'm doing the following jQuery call:
$.getJSON(
"http://localhost:9000/user?name=",
"test",
function(data) {
alert(data.aaData[0]);}
);
but it doesn't work because the data param "test" will be "&test" in the actual call (at least that's what firebug tells me).
I'm a total beginner with JavaScript and jQuery, can anyone tell me how to remove the &-sign in front of the data param?
So that the actual call is http://localhost:9000/user?name=data and not http://localhost:9000/user?name=&data
You could pass the data as an object, like this:
$.getJSON(
"http://localhost:9000/user",
{ name: "test" },
function(data) {
alert(data.aaData[0]);
}
);
The data-object will then be converted to a string and URL-encoded before it is added to the URL. From the jQuery documentation of .getJSON():
If the value of the data parameter is an object (map), it is converted
to a string and url-encoded before it is appended to the URL.
You have to set the get variables to be sent in the correct way:
$.getJSON("http://localhost:9000/user", "name=test", function(data) {
alert(data.aaData[0]);
});

Categories