I am currently trying to get contents from a JSON object.
I've been looking all over google and what I think should work, for some reason, does not.
The JSON looks something like this:
{"locatie0":{"naam0":["Domplein"],"value0":["value1"]},"locatie1":{"naam1":["Neude"],"value1":["value1"]},"locatie2":{"naam2":["Vredenburg"],"value2":["value1"]},"locatie3":{"naam3":["Stadhuisbrug"],"value3":["value1"]},"locatie4":{"naam4":["Korte Minrebroederstraat"],"value4":["value1"]}}
I use below code to read the file but for some reason it will always return undefined or NaN.
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data.locatie[k].naam[k];
// Should alert "Domplein", "Neude", "Vredenburg", "Stadhuisbrug", "Korte Minrebroekstraat",
alert(_locaties);
}
}
});
Can anybody see if i've made any mistakes in my code or if there's a better way to read the values?
locatie[k] tries to access the property k of the object in locatie, but in your case, the number is part of the name itself. You have to build the property name dynamically. In addition, each property of the nested objects is an array with one element, so you have to access the first element:
var _locaties = data['locatie' + k]['naam' + k][0];
Your data structure is a bit strange though. The numbers in the property names makes accessing the data more difficult. If you can change it, change it to an array of objects and don't use arrays for the properties if you don't need them:
[{"naam": "Domplein", "value": "value1"}, {"naam": "Neude", "value":"value1"}]
Then accessing the data is simply:
for (var i = 0, l = data.length; i < l; i++) {
var _locaties = data[i].naam;
}
A JSON does not guarantee any order like an array.
But in your case, the keys of the JSON have index hints, so try accessing "naam" with:
data["locatie" + k]["naam" + k]
Try this:
$.ajax({
url: "_data/pleinen.json",
type: 'get',
dataType: "json",
success: function(data) {
for(var k = 0; k < _loc.length; k += 1) {
var _locaties = data['locatie'+k]['naam'+k][0];
alert(_locaties);
}
}
});
As the value of naam property is array you need to fetch first item from it in order to get string value.
The locatie and the naam are not arrays, so you cannot access them like the way you do.
You have to combine the number with the name as a string. Something like that
data['locatie'+k]
try this ;
k = 0;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);
k = 1;
console.log(
data[ 'locatie'+ k]['naam'+ k][0],
data[ 'locatie'+ k]['value'+ k ][0]
);
Related
I have a JSON array which is returned from my PHP ajax call. I need to loop through it and display all the information. I can not seem to get a method working. I am used to using the foreach key => value, in PHP but that doesn't seem to be an option here.
my array is
[{"Type":"Person","Durable":"Durable","Url":"test.com"},
{"Type":"Person","Durable":"Durable","Url":"test2.com"},
{"Type":"Person","Durable":"Durable","Url":"test3.com"},
{"Type":"Person","Durable":"Durable","Url":"test4.com"},
{"Type":"Location","Durable":"Durable","Url":"test5.com"},
{"Type":"Phone","Durable":"Durable","Url":"test6.com"}]
The length of the array changes every time it is not always 6 items.
And the loop is going to go in my success handler. I just need help on how to access the data.
success: function(data){
}
You can use a simple loop statement:
success: function(data){
var i, l;
for (i = 0, l = data.length; i < l; i++) {
// access the object: data[i]
console.log(data[i]);
}
}
This is the most effiecient way.
You can just loop through the array:
success: function(data){
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var type = obj.Type;
var durable = obj.Durable;
var url = obj.Url;
// do work
}
}
You can use the array prototype forEach:
data.forEach(function(item) {
var type = item["Type"];
var durable = item["Durable"];
/*...*/
});
So i have a javascript function. It performs one ajax call, to retrieve a json object full of data. Within the success function of that ajax call i perfrom ANOTHER ajax call to retrieve the names of the columns of data for that particular set. (yes i'm sure there's a better way but thats not my issue). At this point in time i have two variables: items(json array) and interfaceCols(just an array of strings). Then i try to create an html string to create a table with said data.
Here is my code which will make everything more clear:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
interfaceCols = data.split(" ");
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
console.log(items[i].interfaceCols[4]);
for(j = 0; j < interfaceCols.length; j++){
myString = myString + '<td id = "visibleDef">' + items[i].interfaceCols[j] +'</td>';
}
myString = myString + '</tr>';
interfaces.push(myString);
}
});
}
});
My javascript file throws an error on the "myString = myString + '<td id ='... line.
I am almost positive that it is because i'm just placing a string at the end of "items[i]" with ".interfaceCols[j]"
Can anybody suggest a way to do this? The whole point is so that i dont have to manually type out every column name, because i have alot of tables and each table has many columns.
Given a JS object s:
s = {a: 1, b: 2}
You have (at least) two options to access an attribute:
s.a // returns 1
Which seems to be what you are trying to do right now. To access it with a dynamic name, you can use:
s['a'] // returns 1
In your case, it should be:
items[i][interfaceCols[4]]
I am doing this:
var a_survey = $('#survey-1 :input').serializeArray();
$.ajax({
url: "/save_a_survey/",
type: "post",
data: a_survey,
csrfmiddlewaretoken:'{{ csrf_token }}',
});
Which passes this:
csrfmiddlewaretoken:6rS9oNMSJIzJw6ye8nCQZPRkjNemyMOD
form-1-student:12
form-1-behavior_type:Externalizer
form-1-surveyset:13
But I want to change the names of the keys to:
csrfmiddlewaretoken:6rS9oNMSJIzJw6ye8nCQZPRkjNemyMOD
student:12
behavior_type:Externalizer
surveyset:13
This probably seems like quite a hack, but I am dealing with django formsets and trying to save pieces of them at a time; Which may also sound like a hack...
So far I have tried this:
a_survey = $('#survey-1 :input').serializeArray();
for (var i = 1; i <= a_survey.length; i++) {
a_survey[i]['name'] = a_survey[i]['name'].replace(/form-\d-/g, "");
};
But I keep getting...
TypeError: Cannot read property 'name' of undefined
Thanks for the help
You have an off-by-one error in your iteration (JavaScript arrays are zero-based).
var a_survey = $('#survey-1 :input').serializeArray();
for (var i = 0; i < a_survey.length; i++) {
a_survey[i].name = a_survey[i].name.replace(/form-\d-/g, "");
};
Edit: Alternatively, you can use $.each(), per #RobG's suggestion:
var a_survey = $('#survey-1 :input').serializeArray();
$.each(a_survey, function(i, item) {
item.name = item.name.replace(/form-\d-/g, "");
});
I have an object in my javascript which looks like this:
{"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}},
// .....
What I would like to do is to iterate thru the contents of my object so that I will be able to push them to their respective arrays independently.
I have an array for longitude, latitude, color and level.
So I have tried the following:
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
alert(result.data[size]);
}
-->But this only alerts me "[object Object]"
success: function(result){
var size = 0, key;
for (key in result) {
for(var attr in key){
alert(attr['latitude']);
}
}
}
-->This gives me Undefined result[key]
I have checked that the size of my object is only 1 thru these codes
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
}
alert(size);
I believe that only "data" is being read. And others that are inside "data" are disregarded.
I have read this, this, enter link description here, and this but they sall seem to deal with a different structure of objects. Thanks for the help in advanced.
UPDATE
Using the console.log(), I have confirmed, if im not mistaken that only the first attribute is being fetched
t
Object { level="35", longtitude="121.0508", latitude="14.6204083333333", more...}
color "#040098"
latitude "14.6204083333333"
level "35"
longtitude "121.0508"
I tried this
for (key in result) {
if (result.hasOwnProperty(key)) size++;
console.log(result.data[size]['level']);
}
--> but it says undefined
based on the structure of my object which is
data:[{"t":{'others'},'others'...]
How am I to read everything inside "data"? Each "data" has "t".
Update: Using the for...in construct for iterating over arrays isn't recommended. The alternative is a regular for loop (each method of course having their respective advantages):
for(var i=0; i<results.data.length; i++){
alert(results.data[i]['t']['latitude']);
// etc...
}
Be careful with the structure of your JSON. Also note that the javascript foreach loop iterates over keys/indices -- not values. See demo: http://jsfiddle.net/g76tN/
success: function(result){
var latitudes = [];
// and so on...
for (var idx in result.data ) {
if( result.data.hasOwnProperty(idx) ){
alert( result.data[idx]['t']['latitude'] );
// So you would do something like this:
latitudes.push ( result.data[idx]['t']['latitude'] );
// and so on...
}
}
}
Note for collecting properties of objects in an array, jQuery $.map() -- or native js array map for that matter -- is a neat, useful alternative.
var latitudes = $.map( result.data, function(n){
return n['t']['latitude'];
});
// and so on...
Assuming result is your object, this should just be a matter of iterating over your data array:
for (var i = 0; i < result.data.length; ++i) {
console.log(result.data[i].t.latitude);
...
}
It's not hard to do, as shown below. But why would you want to take useful objects like your t's and turn them into such arrays?
var levels = [], longitudes= [], latitudes = [], colors = [];
var result = {"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}}
]};
var data = result.data;
var i, len, t;
for (i = 0, len = data.length; i < len; i++) {
t = data[length].t;
levels[i] = t.level;
longitudes[i] = t.longtitude;
latitudes[i] = t.latitude;
colors[i] = t.color;
}
See http://jsfiddle.net/VGmee/, which keeps the hasOWnProperty (which is important), and your misspelling of "longitude", which is not.
var data = input.data,
result = {level: [], longtitude: [], latitude: [], color: []};
for (var i = 0, n = data.length; i < n; i += 1) {
var info = data[i].t;
for (var property in info) {
if (info.hasOwnProperty(property)) {
result[property].push(info[property]);
}
}
}
console.log(result.level);
console.log(result.latitude);
console.log(result.longtitude);
console.log(result.color);
This requires the result arrays to actually have the properties in your input array, but you can add error handling as desired.
I am returning a List<> from a webservice as a List of JSON objects. I am trying to use a for loop to iterate through the list and grab the values out of the properties. This is a sample of the returning JSON:
{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
"EmployeeName":"Janet Leverling",
"EmployeeTitle":"Sales Representative",
"RequiredDate":"\/Date(839224800000)\/",
"OrderedProducts":null}]}
So I am trying to extract the contents using something like this:
function PrintResults(result) {
for (var i = 0; i < result.length; i++) {
alert(result.employeename);
}
How should this be done?
Be careful, d is the list.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}
had same problem today, Your topic helped me so here goes solution ;)
alert(result.d[0].EmployeeTitle);
It's close! Try this:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Update:
If your result is truly is an array of one object, then you might have to do this:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
Or if you want to loop through each result in the array if there are more, try:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}
Here it is:
success:
function(data) {
$.each(data, function(i, item){
alert("Mine is " + i + "|" + item.title + "|" + item.key);
});
}
Sample JSON text:
{"title": "camp crowhouse",
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}
Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].
$.each(result.d,function(i) {
// In case there are several values in the array 'd'
$.each(this,function(j) {
// Apparently doesn't work...
alert(this.EmployeeName);
// What about this?
alert(result.d[i][j]['EmployeeName']);
// Or this?
alert(result.d[i][j].EmployeeName);
});
});
That should work. if not, then maybe you can give us a longer example of the JSON.
Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
This will work!
$(document).ready(function ()
{
$.ajax(
{
type: 'POST',
url: "/Home/MethodName",
success: function (data) {
//data is the string that the method returns in a json format, but in string
var jsonData = JSON.parse(data); //This converts the string to json
for (var i = 0; i < jsonData.length; i++) //The json object has lenght
{
var object = jsonData[i]; //You are in the current object
$('#olListId').append('<li class="someclass>' + object.Atributte + '</li>'); //now you access the property.
}
/* JSON EXAMPLE
[{ "Atributte": "value" },
{ "Atributte": "value" },
{ "Atributte": "value" }]
*/
}
});
});
The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.
I have the following call:
$('#select_box_id').change(function() {
var action = $('#my_form').attr('action');
$.get(action,{},function(response){
$.each(response.result,function(i) {
alert("key is: " + i + ", val is: " + response.result[i]);
});
}, 'json');
});
The structure coming back from the server look like:
{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}