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

标签 javascript json html 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 网站以 JSON 格式返回数据,也以 XML 格式返回数据,但我不想使用其他格式检索数据,因为到目前为止,我可以通过查看网络上的其他代码来查看网页上的 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

最佳答案

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

看看这段代码是否适合你,我对 json 数组中的项目进行了测试并且它有效,

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

    var str = "";

    var header = "";

    header += "itemId,"
    header += "title,"
    header += "globalId,"
    header += "primaryCategory.categoryId,"
    header += "primaryCategory.categoryName,"
    header += "galleryURL,"
    header += "viewItemURL,"
    header += "paymentMethod,"
    header += "autoPay,"
    header += "location,"
    header += "country,"
    header += "shippingInfo.shippingServiceCost.currencyId,"
    header += "shippingInfo.shippingServiceCost.value," 
    header += "shippingInfo.shippingType,"
    header += "shippingInfo.shipToLocations,"
    header += "shippingInfo.expeditedShipping,"
    header += "shippingInfo.oneDayShippingAvailable,"
    header += "shippingInfo.handlingTime,"
    header += "sellingStatus.currentPrice.currencyId,"
    header += "sellingStatus.currentPrice.value,"
    header += "sellingStatus.convertedCurrentPrice.currencyId,"
    header += "sellingStatus.convertedCurrentPrice.value,"
    header += "sellingStatus.bidCount,"
    header += "sellingStatus.sellingState,"
    header += "sellingStatus.timeLeft,"
    header += "listingInfo.bestOfferEnabled,"
    header += "listingInfo.buyItNowAvailable,"
    header += "listingInfo.startTime,"
    header += "listingInfo.endTime,"
    header += "listingInfo.listingType,"
    header += "listingInfo.gift,"
    header += "returnsAccepted,"
    header += "galleryPlusPictureURL,"
    header += "condition.conditionId,"
    header += "condition.conditionDisplayName,"
    header += "isMultiVariationListing,"
    header += "topRatedListing";
    header += "\r\n";

    str  += line;

    for (var i = 0; i < array.length; i++) {
        var line = "";

        var JsonObj = array[i];
        line += JsonObj["itemId"]+",";
        line += JsonObj["title"]+",";
        line += JsonObj["globalId"]+",";

        var primaryCategory = JsonObj["primaryCategory"];
        line += primaryCategory[0]["categoryId"]+",";
        line += primaryCategory[0]["categoryName"]+",";

        line += JsonObj["galleryURL"]+",";
        line += JsonObj["viewItemURL"]+",";
        line += JsonObj["paymentMethod"]+",";
        line += JsonObj["autoPay"]+",";
        line += JsonObj["location"]+",";
        line += JsonObj["country"]+",";

        var shippingInfo = JsonObj["shippingInfo"];
        var shippingServiceCost = shippingInfo[0]["shippingServiceCost"];
        line += shippingServiceCost[0]["@currencyId"]+",";
        line += shippingServiceCost[0]["value"]+",";
        line += shippingInfo[0]["shippingType"]+",";
        line += shippingInfo[0]["shipToLocations"]+",";
        line += shippingInfo[0]["expeditedShipping"]+",";
        line += shippingInfo[0]["oneDayShippingAvailable"]+",";
        line += shippingInfo[0]["handlingTime"]+",";

        var sellingStatus = JsonObj["sellingStatus"];
        var currentPrice = sellingStatus[0]["currentPrice"];
        var convertedCurrentPrice = sellingStatus[0]["convertedCurrentPrice"];
        line += currentPrice[0]["@currencyId"]+",";
        line += currentPrice[0]["value"]+",";
        line += convertedCurrentPrice[0]["@currencyId"]+",";
        line += convertedCurrentPrice[0]["value"]+",";
        line += sellingStatus[0]["bidCount"]+",";
        line += sellingStatus[0]["sellingState"]+",";
        line += sellingStatus[0]["timeLeft"]+",";

        var listingInfo = JsonObj["listingInfo"];
        line += listingInfo[0]["bestOfferEnabled"]+",";
        line += listingInfo[0]["buyItNowAvailable"]+",";
        line += listingInfo[0]["startTime"]+",";
        line += listingInfo[0]["endTime"]+",";
        line += listingInfo[0]["listingType"]+",";
        line += listingInfo[0]["gift"]+",";
        line += JsonObj["returnsAccepted"]+",";
        line += JsonObj["galleryPlusPictureURL"]+",";

        var condition = JsonObj["condition"];
        line += condition[0]["conditionId"]+",";
        line += condition[0]["conditionDisplayName"]+",";
        line += JsonObj["isMultiVariationListing"]+",";
        line += JsonObj["topRatedListing"];

        line += '\r\n';

        str  += line;

    }

    return str;

关于javascript - 如何从 eBay api 获取 Json 数据以保存为 CSV 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30277113/

相关文章:

javascript - 如何使 Canvas 调整大小

php - Composer : required packages with differing levels of minimum-stability

json - youtube视频信息json对象给出错误

python - JSON 到 iOS 字符串文件

javascript - 滚动到顶部而不触发scroll()

javascript - ng-click后如何将值传递给ng-if?

c# - 电子邮件格式的字符串变成超链接

javascript - 如何使用 HTML5 Canvas 找出圆的哪一部分被点击?

javascript - ReactJs 复选框值和日期未在状态中更新

javascript - 如何使用 PDF.js 显示 PDF(以 Base64 存储)中的所有页面?