【问题标题】:JQuery parsing only portion of JSONJQuery 只解析 JSON 的一部分
【发布时间】:2016-06-02 23:23:06
【问题描述】:

在解析相当复杂的 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":[""]}
},

] }"

我只需要解析所有的Addresses并提取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 

【问题讨论】:

    标签: javascript jquery json


    【解决方案1】:
    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>

    【讨论】:

    • 对不起,但没有帮助。它抱怨'未捕获的类型错误:无法读取未定义的属性'reduce'。因为我看到 data.results 是未定义的。
    • @grek 您需要将数据变量设置为从服务器或其他接收到的 JSON 对象。 “结果”是 JSON 对象中的结果数组。我将编辑我的答案以包含几个演示。
    • 谢谢艾哈迈德! - 这有帮助。很抱歉延迟回复。遇到具有相同功能的另一个问题。 stackoverflow.com/questions/37662508/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多