Reputation: 55
Probably a simple one for an expert:
I have a json file called newport.json located in the www folder. The json is as follows:
{"nmech":"3.00","nelect":"3.00","nplant":"0.00","ncivil":"55.00"}
I have my JS to load in via ajax:
$.ajax({
url:'newport.json',
datatype:'json',
type:'get',
cache:false,
success:function(data){
$(data).each(function(index,value){
console.log(value);
});
}
});
My issue is the console log produces the following from the above js:
Object {nmech: "3.00", nelect: "3.00", nplant: "0.00", ncivil: "55.00"}
but I seem to be struggling to then get a value say nmech passed into a javascript variable.
Thanks in advance for any help.
Upvotes: 0
Views: 981
Reputation: 1955
Your json is an object, not array. As soon as you don't have anything to enumerate, $.each doen's make much sense here.
To to access you properties you need:
var nmech = data.nmech;
var nelect = data.nelect;
etc
Upvotes: 1
Reputation: 420
As there is a single object that is returned, the loop only runs once. I believe what you are trying to do is to enumerate the properties of that single object. So this:
for (var propertyName in data) { console.log(data[propertyName]; }
Upvotes: 0