【问题标题】:How do I count the number of unique key:value pairs in JSON data? [closed]如何计算 JSON 数据中唯一键:值对的数量? [关闭]
【发布时间】:2014-03-26 20:41:39
【问题描述】:

我的函数正在返回以下格式的 JSON 数据:

"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"
                       ]
                    }
                 ],
                 "galleryURL":[
                    "http:\/\/thumbs4.ebaystatic.com\/m\/mGwHzpyvkph9-nU12sCspxw\/140.jpg"
                 ],
                 "viewItemURL":[
                    "http:\/\/www.ebay.com\/itm\/Apple-iPhone-4-clean-esn-Black-Verizon-Smartphone-\/151258132867?pt=Cell_Phones"
                 ],
                 "productId":[
                    {
                       "@type":"ReferenceID",
                       "__value__":"101787954"
                    }
                 ],
                 "paymentMethod":[
                    "PayPal"
                 ],
                 "autoPay":[
                    "false"
                 ],
                 "postalCode":[
                    "93905"
                 ],
                 "location":[
                    "Salinas,CA,USA"
                 ],
                 "country":[
                    "US"
                 ],
                 "shippingInfo":[
                    {
                       "shippingServiceCost":[
                          {
                             "@currencyId":"USD",
                             "__value__":"0.0"
                          }
                       ],
                       "shippingType":[
                          "Free"
                       ],
                       "shipToLocations":[
                          "US"
                       ],
                       "expeditedShipping":[
                          "true"
                       ],
                       "oneDayShippingAvailable":[
                          "false"
                       ],
                       "handlingTime":[
                          "2"
                       ]
                    }
                 ],
                 "sellingStatus":[
                    {
                       "currentPrice":[
                          {
                             "@currencyId":"USD",
                             "__value__":"96.0"
                          }
                       ],
                       "convertedCurrentPrice":[
                          {
                             "@currencyId":"USD",
                             "__value__":"96.0"
                          }
                       ],
                       "bidCount":[
                          "17"
                       ],
                       "sellingState":[
                          "Active"
                       ],
                       "timeLeft":[
                          "P0DT0H0M11S"
                       ]
                    }
                 ],
                 "listingInfo":[
                    {
                       "bestOfferEnabled":[
                          "false"
                       ],
                       "buyItNowAvailable":[
                          "false"
                       ],
                       "startTime":[
                          "2014-03-19T18:29:51.000Z"
                       ],
                       "endTime":[
                          "2014-03-26T18:29:51.000Z"
                       ],
                       "listingType":[
                          "Auction"
                       ],
                       "gift":[
                          "false"
                       ]
                    }
                 ],
                 "returnsAccepted":[
                    "false"
                 ],
                 "condition":[
                    {
                       "conditionId":[
                          "3000"
                       ],
                       "conditionDisplayName":[
                          "Used"
                       ]
                    }
                 ],
                 "isMultiVariationListing":[
                    "false"
                 ],
                 "topRatedListing":[
                    "false"
                 ]
              },
              {
                 "itemId":[
                    "360810145746"
                 ],
                 "title":[
                    "U Apple iPhone 3GS - 8GB - Black (FACTORY UNLOCKED) Smartphone (C)"
                 ],
                 "globalId":[
                    "EBAY-US"
                 ],
                 "subtitle":[
                    "****USA SELLER*****FAST SHIPPING*****TOP SELLER****"
                 ],
                 "primaryCategory":[
                    {
                       "categoryId":[
                          "9355"
                       ],
                       "categoryName":[
                          "Cell Phones & Smartphones"
                       ]
                    }
                 ],
                 "galleryURL":[
                    "http:\/\/thumbs3.ebaystatic.com\/m\/mQGXy5hucEtqk6inUKFu67g\/140.jpg"
                 ],
                 "viewItemURL":[
                    "http:\/\/www.ebay.com\/itm\/U-Apple-iPhone-3GS-8GB-Black-FACTORY-UNLOCKED-Smartphone-C-\/360810145746?pt=Cell_Phones"
                 ],
                 "productId":[
                    {
                       "@type":"ReferenceID",
                       "__value__":"99984545"
                    }
                 ],
                 "paymentMethod":[
                    "PayPal"
                 ],
                 "autoPay":[
                    "true"
                 ],
                 "postalCode":[
                    "10001"
                 ],
                 "location":[
                    "New York,NY,USA"
                 ],
                 "country":[
                    "US"
                 ],
                 "shippingInfo":[
                    {
                       "shippingServiceCost":[
                          {
                             "@currencyId":"USD",
                             "__value__":"0.0"
                          }
                       ],
                       "shippingType":[
                          "Free"
                       ],
                       "shipToLocations":[
                          "US",
                          "CA",
                          "GB",
                          "AU",
                          "FR",
                          "HK",
                          "MT",
                          "IE",
                          "IL",
                          "NZ",
                          "PH",
                          "SG"
                       ],
                       "expeditedShipping":[
                          "true"
                       ],
                       "oneDayShippingAvailable":[
                          "false"
                       ],
                       "handlingTime":[
                          "1"
                       ]
                    }
                 ],
                 "sellingStatus":[
                    {
                       "currentPrice":[
                          {
                             "@currencyId":"USD",
                             "__value__":"84.95"
                          }
                       ],
                       "convertedCurrentPrice":[
                          {
                             "@currencyId":"USD",
                             "__value__":"84.95"
                          }
                       ],
                       "sellingState":[
                          "Active"
                       ],
                       "timeLeft":[
                          "P12DT0H9M11S"
                       ]
                    }
                 ],
                 "listingInfo":[
                    {
                       "bestOfferEnabled":[
                          "false"
                       ],
                       "buyItNowAvailable":[
                          "false"
                       ],
                       "startTime":[
                          "2013-12-08T18:33:51.000Z"
                       ],
                       "endTime":[
                          "2014-04-07T18:38:51.000Z"
                       ],
                       "listingType":[
                          "StoreInventory"
                       ],
                       "gift":[
                          "false"
                       ]
                    }
                 ],
                 "returnsAccepted":[
                    "true"
                 ],
                 "condition":[
                    {
                       "conditionId":[
                          "3000"
                       ],
                       "conditionDisplayName":[
                          "Used"
                       ]
                    }
                 ],
                 "isMultiVariationListing":[
                    "false"
                 ],
                 "discountPriceInfo":[
                    {
                       "originalRetailPrice":[
                          {
                             "@currencyId":"USD",
                             "__value__":"449.0"
                          }
                       ],
                       "pricingTreatment":[
                          "STP"
                       ],
                       "soldOnEbay":[
                          "false"
                       ],
                       "soldOffEbay":[
                          "false"
                       ]
                    }
                 ],
                 "topRatedListing":[
                    "true"
                 ]
              }

等等。每个项目都属于某个 categoryId。因此,例如在这种情况下,我想做的是计算每个唯一 categoryId 出现的次数,然后将前两个 categoryId 存储在一个数组中。我认为这可以通过 For 循环来完成,但我不确定如何设置。任何帮助表示赞赏,谢谢!

【问题讨论】:

  • 您说“每个项目都属于某个 categoryId”,但您只显示一个包含类别 ID 的对象。你可能想要更清楚。这些都将在层次结构中处于同一级别吗?它们会嵌套吗?
  • 我在代码中添加了第二个项目结果以显示嵌套的外观。如果您需要我添加任何其他内容,请告诉我。

标签: javascript json sorting ebay-api


【解决方案1】:

这应该可行:

var o = {};
data.searchResult[0].item.forEach(function(item) {
    var id = item.primaryCategory[0].categoryId;
    if (o[id]) o[id]++;
    else o[id] = 1;
});
var top2 = Object.keys(o).sort(function(a, b) { return o[b]-o[a]; }).slice(0, 2);
console.log('Top two categories: ' + top2.join(', '));

【讨论】:

  • 大部分都是有道理的,你能解释一下这里发生了什么吗?:{ return o[b]-o[a]; }).slice(0, 2); console.log('Top two categories: ' + top2.join(', '))
  • 按出现次数降序对类别 ID 进行排序,切掉前两个类别,并将它们打印到控制台。
  • 最后一个问题,你为什么使用“[0]”作为 searchResult 和 primaryCategory?
  • @ghobs 从您的示例数据来看,它们都是包含一个对象的数组。这似乎只是一个奇怪的 eBay 设计决定;我查找了其他一些 eBay JSON 解析代码,它会像这个答案一样深入到第一个元素。
【解决方案2】:

循环通过searchResult.item 并将categoryIds 存储在<CategoryID, NumOccurences> 的哈希中

var categoryIds = {};
for (var i = 0, l = searchResult.item.length; i < l; i++) {
    var categoryId = searchResult.item[i].primaryCategory.categoryId;
    categoryIds[categoryId] = ++(categoryIds[categoryId] || 0);
}

// console.log(categoryIds);
// > { '1234': 1, '2345': 2, ... }

【讨论】:

  • 如果我错了请纠正我,但它不应该是searchResult.length,所以它会循环遍历searchResult中的所有项目吗?我收到一条错误消息,指出当我尝试运行它时未定义 searchResult,不确定是否是导致它的原因。
  • 从您发布的 JSON 来看,searchResult.item 是项目数组。如果数组是不同的对象,只需替换 searchResult.item 即可。
猜你喜欢
  • 1970-01-01
  • 2018-02-20
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多