JSON iteration using jquery

2019-08-19 21:12发布

问题:

I have called rest api through ajax, i get the response from api in json format, now i want to display the data on my webpage. I want to show as follows

scheduled
driver_count:
passenger_count:

active
driver_count:
passenger_count:

My code as follows

$(document).ready(function() {
        $.ajax({
            asyn: true,
            crossDomain: true,
            url: "http://10.26.32.11/api/rating-service/rate/current/gettrips",
            dataType: 'JSON',
            callback: 'callback',
            type: 'GET',
            success: function(data) {
                var jso = parseJSON(data);
                console.log(jso);                    

            }
        });

    });

JSON reply

{
"scheduled": {
    "driver_count": 1,
    "passenger_count": 1
},
"active": {
    "driver_count": 0,
    "passenger_count": 0
}

}

回答1:

You can create new variable as key_count with value and use that variable

obj = {
"scheduled": {
    "driver_count": 1,
    "passenger_count": 1
},
"active": {
    "driver_count": 0,
    "passenger_count": 0
}}
makeFlatModel(obj);
console.log(obj);

function makeFlatModel(jsonObject){
	var sum=0;
	for(var propertyName in jsonObject){
		if(typeof jsonObject[propertyName] =='object'){
			jsonObject[propertyName+"_count"] = makeFlatModel(jsonObject[propertyName]);
		}else{
			sum+= jsonObject[propertyName];
		}
	} 
  return sum;

}

Output



回答2:

Here:

// jsonreplay is the string of json you got from the server
var obj = JSON.parse(jsonreplay)
// in javascript you can use for loop to iterate properties
for(var propertyName in obj){
   console.log(propertyName+":");
   for(var internalPropertyName in obj[propertyName]){
      console.log(internalPropertyName + ":"+obj[propertyName][internalPropertyName]);
   }
}


回答3:

You can access your variables as per below

jso.active.driver_count // will print out your value


回答4:

if you did not make this api by yourself, you can loop object by

var jsobj = {
            "scheduled": {
                            "driver_count": 1,
                            "passenger_count": 1
                         },
            "active":    {
                         "driver_count": 0,
                         "passenger_count": 0
                         }
            };

for (var key in jsobj) {
    if (jsobj.hasOwnProperty(key)) {
        console.log(key); //scheduled, active
        var d_cnt = jsobj[key]['driver_count'];
        var p_cnt = jsobj[key]['passenger_count'];
    }
}    

but if you can edit api output script, this structure will make life easier:

var objList = [{
            "type" : "scheduled", 
            "driver_count": 1,
            "passenger_count": 1
          },{
            "type": "active",
            "driver_count": 0,
            "passenger_count": 0
          }];