如何从eBay api获取Json数据以CSV格式保存?

时间:2015-05-16 14:54:15

标签: javascript json html5 ebay-api

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>eBay Search Results</title>
  <style type="text/css">body { font-family: arial,sans-serif;} </style>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
</head>
<body>
<h1>JSON</h1>
<pre id="results"></pre>
<h1>CSV</h1>
<pre id="csv"></pre>


<script>



//Function that create JSON to CSV format.
function ConvertToCSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            line += array[i][index];
        }

        str += line + '\r\n';
    }

    return str;
}

// Parse the response and build an HTML table to display search results
function _cb_findItemsByKeywords(root) {
    var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];

    for (var i = 0; i < items.length; ++i) {
        var item     = items[i];
        var title    = item.title;
        var pic      = item.galleryURL;
        var viewitem = item.viewItemURL;
       }
    var jsonObject = JSON.stringify(items);
    // Display JSON
    $('#results').text(jsonObject);
    //Convert JSON to CSV & Display CSV
    $('#csv').text(ConvertToCSV(jsonObject));
 }  // End _cb_findItemsByKeywords() function

// Construct the request
// Replace MyAppID with your Production AppID
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=APIID";
url += "&GLOBAL-ID=EBAY-US";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
url += "&keywords=harry%20potter";
url += "&paginationInput.entriesPerPage=3";

// Submit the request
s=document.createElement('script'); // create script element
s.src= url;
document.body.appendChild(s);

</script>


</body>
</html>

当我在上面的代码中的字段APIID中设置我的Developer API ID并运行时,它会在网页上显示JSON和CSV格式。但是我无法将这个在网页上显示的csv数据保存到我的本地硬盘上。

我看到一些php的代码可以创建文件并保存在硬盘上,但是我无法使用这段代码。

我是新手,我在eBay上有300个产品的大量库存,我需要在csv格式下载,所以我可以提供给其他电子商务网站。

eBay网站也以XML格式返回JSON格式的数据,但我不想采用其他格式的检索数据,因为到目前为止,我可以通过查看网页上的其他代码来查看网页上的CSV数据并使其与上面粘贴的eBay开发者网站上的示例代码一起使用。

我得到的输出是: -

JSON

[{"itemId":["171430021529"],"title":["New Harry Potter Hermione Granger Rotating Time Turner Necklace Gold Hourglass"],"globalId":["EBAY-US"],"primaryCategory":[{"categoryId":["29798"],"categoryName":["Harry Potter"]}],"galleryURL":["http://thumbs2.ebaystatic.com/m/mqajRbE-6CfHvlB64wNF5Ew/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/New-Harry-Potter-Hermione-Granger-Rotating-Time-Turner-Necklace-Gold-Hourglass-/171430021529?pt=LH_DefaultDomain_0"],"paymentMethod":["PayPal"],"autoPay":["true"],"location":["China"],"country":["CN"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.17"}],"shippingType":["Flat"],"shipToLocations":["Worldwide"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["3"]}],"sellingStatus":[{"currentPrice":[{"@currencyId":"USD","__value__":"1.48"}],"convertedCurrentPrice":[{"@currencyId":"USD","__value__":"1.48"}],"sellingState":["Active"],"timeLeft":["P2DT0H54M52S"]}],"listingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2014-08-22T04:09:56.000Z"],"endTime":["2015-05-19T04:14:56.000Z"],"listingType":["FixedPrice"],"gift":["false"]}],"returnsAccepted":["true"],"galleryPlusPictureURL":["http://galleryplus.ebayimg.com/ws/web/171430021529_1_0_1.jpg"],"condition":[{"conditionId":["1000"],"conditionDisplayName":["New"]}],"isMultiVariationListing":["false"],"topRatedListing":["false"]},{"itemId":["221770537517"],"title":["Harry Potter Hogwarts Crest Logo and Motto Golden School Badge Charms Necklace"],"globalId":["EBAY-US"],"primaryCategory":[{"categoryId":["155101"],"categoryName":["Necklaces & Pendants"]}],"galleryURL":["http://thumbs2.ebaystatic.com/m/mMm2s0grYJYAnjAVz8pa-Ug/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/Harry-Potter-Hogwarts-Crest-Logo-and-Motto-Golden-School-Badge-Charms-Necklace-/221770537517?pt=LH_DefaultDomain_0"],"paymentMethod":["PayPal"],"autoPay":["false"],"location":["China"],"country":["CN"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["1"]}],"sellingStatus":[{"currentPrice":[{"@currencyId":"USD","__value__":"0.92"}],"convertedCurrentPrice":[{"@currencyId":"USD","__value__":"0.92"}],"bidCount":["6"],"sellingState":["Active"],"timeLeft":["P0DT0H2M16S"]}],"listingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2015-05-12T03:22:20.000Z"],"endTime":["2015-05-17T03:22:20.000Z"],"listingType":["Auction"],"gift":["false"]}],"returnsAccepted":["true"],"condition":[{"conditionId":["1500"],"conditionDisplayName":["New without tags"]}],"isMultiVariationListing":["false"],"topRatedListing":["false"]},{"itemId":["111668667939"],"title":["Hot Movie Harry Potter Horcruxes Alloy Crystal Ring 8# Crown Vintage Jewelry"],"globalId":["EBAY-US"],"primaryCategory":[{"categoryId":["29798"],"categoryName":["Harry Potter"]}],"galleryURL":["http://thumbs4.ebaystatic.com/m/mj3SFZMMPyUvnkja_iiTikg/140.jpg"],"viewItemURL":["http://www.ebay.com/itm/Hot-Movie-Harry-Potter-Horcruxes-Alloy-Crystal-Ring-8-Crown-Vintage-Jewelry-/111668667939?pt=LH_DefaultDomain_0"],"paymentMethod":["PayPal"],"autoPay":["false"],"location":["China"],"country":["CN"],"shippingInfo":[{"shippingServiceCost":[{"@currencyId":"USD","__value__":"0.0"}],"shippingType":["Free"],"shipToLocations":["Worldwide"],"expeditedShipping":["false"],"oneDayShippingAvailable":["false"],"handlingTime":["1"]}],"sellingStatus":[{"currentPrice":[{"@currencyId":"USD","__value__":"1.25"}],"convertedCurrentPrice":[{"@currencyId":"USD","__value__":"1.25"}],"bidCount":["7"],"sellingState":["Active"],"timeLeft":["P0DT0H4M24S"]}],"listingInfo":[{"bestOfferEnabled":["false"],"buyItNowAvailable":["false"],"startTime":["2015-05-12T03:24:28.000Z"],"endTime":["2015-05-17T03:24:28.000Z"],"listingType":["Auction"],"gift":["false"]}],"returnsAccepted":["true"],"galleryPlusPictureURL":["http://galleryplus.ebayimg.com/ws/web/111668667939_1_0_1.jpg"],"condition":[{"conditionId":["1000"],"conditionDisplayName":["New"]}],"isMultiVariationListing":["false"],"topRatedListing":["false"]}]

CSV

171430021529,New Harry Potter Hermione Granger Rotating Time Turner Necklace Gold Hourglass,EBAY-US,[object Object],http://thumbs2.ebaystatic.com/m/mqajRbE-6CfHvlB64wNF5Ew/140.jpg,http://www.ebay.com/itm/New-Harry-Potter-Hermione-Granger-Rotating-Time-Turner-Necklace-Gold-Hourglass-/171430021529?pt=LH_DefaultDomain_0,PayPal,true,China,CN,[object Object],[object Object],[object Object],true,http://galleryplus.ebayimg.com/ws/web/171430021529_1_0_1.jpg,[object Object],false,false
221770537517,Harry Potter Hogwarts Crest Logo and Motto Golden School Badge Charms Necklace,EBAY-US,[object Object],http://thumbs2.ebaystatic.com/m/mMm2s0grYJYAnjAVz8pa-Ug/140.jpg,http://www.ebay.com/itm/Harry-Potter-Hogwarts-Crest-Logo-and-Motto-Golden-School-Badge-Charms-Necklace-/221770537517?pt=LH_DefaultDomain_0,PayPal,false,China,CN,[object Object],[object Object],[object Object],true,[object Object],false,false
111668667939,Hot Movie Harry Potter Horcruxes Alloy Crystal Ring 8# Crown Vintage Jewelry,EBAY-US,[object Object],http://thumbs4.ebaystatic.com/m/mj3SFZMMPyUvnkja_iiTikg/140.jpg,http://www.ebay.com/itm/Hot-Movie-Harry-Potter-Horcruxes-Alloy-Crystal-Ring-8-Crown-Vintage-Jewelry-/111668667939?pt=LH_DefaultDomain_0,PayPal,false,China,CN,[object Object],[object Object],[object Object],true,http://galleryplus.ebayimg.com/ws/web/111668667939_1_0_1.jpg,[object Object],false,false

1 个答案:

答案 0 :(得分:1)

你的gson数组由列表中每个项目的几乎相同的gson结构组成,没有简单的方法来处理它,但是编写一个long函数来处理json数组中的每个项目。首先添加标题,然后为标题中的每个项目添加一行数据

看看这段代码是否适合你,我在json数组中对它进行了测试,它可以正常工作,

numbs2format <- 
    xyz[, (sapply(xyz, function(x) isTRUE(sum(x %% 1) > 0)))]
# ignore the warnings from trying to use %% on non-numerics
other.columns <- 
    xyz[, (sapply(xyz, function(x) !isTRUE(sum(x %% 1) > 0)))]

cbind(other.columns, format(numbs2format, digits=2, nsmall=2))
#  v1   v2     v3   v4
#1  a 8200 365.21 0.31
#2  b 8100 365.21 0.33