JQuery只解析JSON

时间:2016-06-02 23:23:06

标签: javascript jquery json

解析相当复杂的JSON数据时遇到问题。

我想要实现的是解析json数据,提取地址信息并在typeahead下拉列表中填充它。

JSON数据:

"{
"Version":"2.0.20",
"ResultCode":"XS02",
"ErrorString":"",
"Results":
[
{"Address":
    {"AddressLine1":"300 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501","CountrySubdivisionCode ":"US-AK","AddressKey":"99501118273","SuiteName":"Apt","SuiteCount":3,"SuiteList":["","Apt A","Apt B"],"PlusFour":["1182","1182","1182"]}
},
{"Address":
    {"AddressLine1":"240 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1150","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115040","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
{"Address":
    {"AddressLine1":"308 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1152","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115208","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},
{"Address":{"AddressLine1":"301 1/2 E Manor Ave","City":"Anchorage","CityAccepted":"","CityNotAccepted":"","State":"AK","PostalCode":"99501-1151","CountrySubdivisionCode ":"US-AK","AddressKey":"99501115101","SuiteName":"","SuiteCount":0,"SuiteList":[""],"PlusFour":[""]}
},

] }"

我只需要解析所有地址并提取AddressLine1 + City + State + PostalCode

JQuery的:

 $('#taquery').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
},
{
    name: 'states',
    displayKey: 'value',        
    source: function (query, process) {
        return $.ajax({
            url: "/addressLookup",
            type: 'get',
            data: { query: query },
            dataType: 'json',
            success: function (data) {
                return typeof data == 'undefined' ? false : processResult(data);
            }
        });
    }
});

var processResult = function (data) {     
var addArray = $.makeArray(data.Results);
$.map(addArray, function (item, i) {
    return (formatAddressJson(item.Address, i));
});   
};

var formatAddressJson = function (addr, idx) {
var rtn;   
rtn = {
    fullAddress: addr.AddressLine1 + ', ' + addr.City + ', ' + addr.State + ', ' + addr.PostalCode,
    addrLine1: addr.AddressLine1,
    city: addr.City,
    state: addr.State,
    zip: addr.PostalCode.substring(0, 5),
    idx: idx
};
return rtn; 
}

错误:

jquery-1.10.2.min.js:4 Uncaught TypeError: Cannot use 'in' operator to search for '2548' in {"Version":"2.0.20","ResultCode":"XS02","ErrorString":"","Results":[{"Address":{"AddressLine1":"300 1/2 E Manor 

1 个答案:

答案 0 :(得分:0)

var data = JSON.parse(response);
var addresses = data.results.reduce(function(agg, cur, idx) {
   agg.push(formatAddress(cur.Address, idx)
   return agg;
}, []);
function formatAddress(adr, idx) { //...your method }
// now you can loop over addresses array and access each.
addresses.forEach(function(addressObject) { console.log(addressObject) });

这段代码应该可以使用,你应该使用reduce方法而不是map,并且你不需要jquery来完成它。

修改

var JSON_FROM_SUCCESS_FUNCTION = {
  "Version": "2.0.20",
  "ResultCode": "XS02",
  "ErrorString": "",
  "Results": [{
    "Address": { "AddressLine1": "300 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501118273", "SuiteName": "Apt", "SuiteCount": 3, "SuiteList": ["", "Apt A", "Apt B"], "PlusFour": ["1182", "1182", "1182"] }
  }, {
    "Address": { "AddressLine1": "240 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1150", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115040", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
  }, {
    "Address": { "AddressLine1": "308 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1152", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115208", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
  }, {
    "Address": { "AddressLine1": "301 1/2 E Manor Ave", "City": "Anchorage", "CityAccepted": "", "CityNotAccepted": "", "State": "AK", "PostalCode": "99501-1151", "CountrySubdivisionCode ": "US-AK", "AddressKey": "99501115101", "SuiteName": "", "SuiteCount": 0, "SuiteList": [""], "PlusFour": [""] }
  }]
};


/*
  $('#taquery').typeahead({
    hint: true,
    highlight: true,
    minLength: 3
}, {
    name: 'states',
    displayKey: 'value',        
    source: function (query, process) {
        return $.ajax({
            url: "/addressLookup",
            type: 'get',
            data: { query: query },
            dataType: 'json',
            success: function (data) {
                return typeof data == 'undefined' ? false : processResult(data);
            }
        });
    }
});

*/

function processResult(data) {
  return data.Results.reduce(function(agg, cur, idx) {
     agg.push(formatAddress(cur.Address, idx));
     return agg;
  }, []);
};

function formatAddress(addr, idx) {
  var fullAddress = addr.AddressLine1 + ', ' + addr.City + ', ' + addr.State + ', ' + addr.PostalCode;
  return {
      fullAddress: fullAddress,
      addrLine1: addr.AddressLine1,
      city: addr.City,
      state: addr.State,
      zip: addr.PostalCode.substring(0, 5),
      idx: idx
  };
}


var addresses = processResult(JSON_FROM_SUCCESS_FUNCTION);

// now you can loop over addresses array and access each.
addresses.forEach(function(addressObject) { console.log(addressObject) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>