JSON解析问题给了我一个“不能读取未定义的属性”#39;错误。

时间:2014-03-28 19:02:32

标签: javascript json api

我正在研究ping eBay的云代码,返回JSON,解析它,并将前两个类别存储到一个数组中。发送到eBay的参数基于用户在iOS应用程序的itemSearch栏中输入的内容。当我尝试发送像" iPhone"这样的查询时,会出现此错误:

TypeError: Cannot read property 'findItemsByKeywordsResponse' of undefined
    at Object.Parse.Cloud.httpRequest.success (main.js:37:15)
    at Object.<anonymous> (<anonymous>:565:19) (Code: 141, Version: 1.2.18)

这是我的Objective-c代码:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if (sender != self.nextButton) return;
    if (self.itemSearch.text.length > 0) {

        [PFCloud callFunctionInBackground:@"eBayCategorySearch"
                           withParameters:@{@"item": self.itemSearch.text}
                                    block:^(NSString *result, NSError *error) {
                                        if (!error) {

                                            NSLog(@"Successfully pinged eBay!");
                                        }

                                    }];


    }

    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.

}

在Parse上运行的云代码(main.js):

Parse.Cloud.define("eBayCategorySearch", function(request, response) {
          url = 'http://svcs.ebay.com/services/search/FindingService/v1';

  Parse.Cloud.httpRequest({
      url: url,
      params: {     
       'OPERATION-NAME' : 'findItemsByKeywords', 
       'SERVICE-VERSION' : '1.12.0',
       'SECURITY-APPNAME' : '*APP ID GOES HERE*',
       'GLOBAL-ID' : 'EBAY-US',
       'RESPONSE-DATA-FORMAT' : 'JSON',
       'itemFilter(0).name=ListingType' : 'itemFilter(0).value=FixedPrice',
       'keywords' : request.params.item,

        // your other params
     },
      success: function (httpResponse) {


          var response = JSON.parse(httpResponse.text)  

          // count number of times each unique primaryCategory shows up (based on categoryId), return top two (done with a for loop?)

          var userCategories = {};


          var data = httpResponse.data
          data.findItemsByKeywordsResponse.searchResult[0].item.forEach(function(item) 
          {
          var id = item.primaryCategory[0].categoryId;
          if (userCategories[id]) userCategories[id]++;
          else userCategories[id] = 1;
          });

          var top2 = Object.keys(userCategories).sort(function(a, b) 
            {return userCategories[b]-userCategories[a]; }).slice(0, 2);
          console.log('Top two categories: ' + top2.join(', '));


          response.success(httpResponse.data)

          // if user has criteria info for one of the categories already, default to that, send to matchcenter

          // if user has criteria for both categories, ask which one, default to selected categories criteria, send to matchcenter

          // if user has no criteria for either category, redirect to criteriaViewController, save the criteria user inputs, send to matchcenter



      // deal with success and respond to query
  },
            error: function (httpResponse) {
                console.log('error!!!');
                console.error('Request failed with response code ' + httpResponse.status);
            }
       });
});

返回时JSON通常如下所示:

{
   "findItemsByKeywordsResponse":[
      {
         "ack":[
            "Success"
         ],
         "version":[
            "1.12.0"
         ],
         "timestamp":[
            "2014-03-26T18:29:40.583Z"
         ],
         "searchResult":[
            {
               "@count":"100",
               "item":[
                  {
                     "itemId":[
                        "151258132867"
                     ],
                     "title":[
                        "Apple iPhone 4 - clean esn - Black (Verizon) Smartphone"
                     ],
                     "globalId":[
                        "EBAY-US"
                     ],
                     "primaryCategory":[
                        {
                           "categoryId":[
                              "9355"
                           ],
                           "categoryName":[
                              "Cell Phones & Smartphones"

我不认为它被正确归还,因此无法找到&#34; findItemsByKeywordsResponse&#34;。有没有办法可以打印出返回的JSON,看看我是否正在解析错误的东西?

1 个答案:

答案 0 :(得分:1)

您正在解析您的回复:

var response = JSON.parse(httpResponse.text)  

但之后你不使用它。您使用的是httpResponse.data

请尝试使用您的response对象:

response.findItemsByKeywordsResponse.searchResult[0]......