简体   繁体   中英

Pass json data to javascript variable

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.

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

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]; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM