使用jQuery进行JSON迭代 [英] JSON iteration using jquery

查看:108
本文介绍了使用jQuery进行JSON迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经通过ajax调用了rest api,我得到了json格式的api响应,现在我想在网页上显示数据. 我想显示如下

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:

我的代码如下

$(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回复

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

}

推荐答案

您可以将新变量创建为具有值的key_count并使用该变量

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;

}

输出

这篇关于使用jQuery进行JSON迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆