按key值查找json数据中对应的值

按key值查找json数据中对应的值


json数据如下:



var data={
    "transport_station_id": "1",
    "transport_station_tel": "13957708561",
    "carrier_driver_id": 0,
    "carrier_driver_name": "李明星",
    "carrier_driver_phone": "188****5026",
    "estimate_arrive_time": null,
    "order_total_delivery_cost": 0,
    "order_total_delivery_discount": 0,
    "order_status": 3,
    "abnormal_code": "",
    "abnormal_desc": "",
    "event_log_details": [
      {
        "order_status": 1,
        "occur_time": 1503296985000,
        "carrier_driver_name": "杨超",
        "carrier_driver_phone": "188****5026"
      },
      {
        "order_status": 20,
        "occur_time": 1503297045000,
        "carrier_driver_name": "李明星",
        "carrier_driver_phone": "188****5026"
      },
      {
        "order_status": 80,
        "occur_time": 1503297105000,
        "carrier_driver_name": "李明星",
        "carrier_driver_phone": "188****5026"
      },
      {
        "order_status": 2,
        "occur_time": 1503297165000,
        "carrier_driver_name": "李明星",
        "carrier_driver_phone": "188****5026"
      },
      {
        "order_status": 3,
        "occur_time": 1503297225000,
        "carrier_driver_name": "李明星",
        "carrier_driver_phone": "188****5026"
      }
    ]
  }

深度遍历json对象:


var arr=[]
function deepTraverse(json,key) {
    // 1. 变量为json对象:将item输出,value进行递归
     if(isType(json, "Object")){
          for(var item in json){
            if (item==key) {
                arr.push(json[key])

            }

           if(isType(json[item], "Array") || isType(json[item], "Object")){

           }
           deepTraverse(json[item],key);
          }
     }
     // 2. 变量为json数组:逐个元素递归
     else if(isType(json, "Array")){
          for(var i=0; ivar jsonObj = json[i];
               deepTraverse(jsonObj,key);
              // 遍历数组中的元素(为json对象)后输出
              if(isType(jsonObj, "Object")){

               }
          }
     }
     // 3. 变量为简单数据类型:直接输出(递归函数的终止条件)
     else if(isType(json, "String") || isType(json, "Number") ||
      isType(json,"Boolean") || isType(json,"Null")){

     }

}

判断json数据类型

function isType(obj,type){
    return Object.prototype.toString.call(obj) ==="[object "+type+"]";
}
deepTraverse(data,'carrier_driver_name')

你可能感兴趣的:(json)