3
<!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>

When I set my Developer API id in the field APIID in above code and run it shows me the JSON and CSV format on the webpage. But I am unable to save this csv data which is showing on webpage to my local hardisk.

I saw some code of php which can create the file and save on hard disk but I am unable to make it work with this code.

I am new to this and I have huge inventory of 300 products on eBay, in which I need to download on csv format so i can provide the same to other e-commerce websites.

The eBay site return the data in JSON format also in XML, but I don't want to go with other format of retrieving data as so far I am able to see the CSV data on webpage by seeing other codes on the web and making it work with the sample code on eBay developer website which is pasted above.

The output I am getting is as :-

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
halfer
  • 19,824
  • 17
  • 99
  • 186
Kapil Soni
  • 47
  • 1
  • 1
  • 10

1 Answers1

1

Your gson array consist of almost the same gson structure for each item in your list, there is no easy way to handle it but to write a long function to handle each item in the json array. First you add the header then you add a row of data for each item in the header,

See if this code works for you, I tested it on item from the json array and it works,

    //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;
faljbour
  • 1,367
  • 2
  • 8
  • 15
  • Thanks for your response and time. I tried your Code to Parse the JSON to CSV Other seems fine accept the primaryCategory, shippingInfo ,sellingStatus,listingInfo,condition. The CSV for these JSON value is showing [object Object] – Kapil Soni May 17 '15 at 11:34
  • I fixed the primaryCategory.categoryId and primaryCategory.categoryName, the other items are fine, you do not display shippingInfo, or listingInfo or condition, you display the content inside of them, such condition.conditionId or sellingStatus.bidCount...., so you should be able to display everything. – faljbour May 17 '15 at 13:19
  • the problem still persist as mentioned above. I am also working on same and if i find any solution would share the same. thanks for your time really appreciate. – Kapil Soni May 18 '15 at 11:50
  • @Kapil Soni, I tested the solution and it works fine. Please make sure that when you are displaying object such as listingInfo or shippingInfo that you follow the recommend method in my answer, such as getting the object for those item then reference the content of the each one, for example, , then access the content by using the zero idnex – faljbour May 18 '15 at 17:37
  • @falijbour It worked perfectly now. Any advice how to make the csv data to save to a file? – Kapil Soni Jun 01 '15 at 13:17
  • Hi there, I didn't notice, that is the code provided is causing the cvs data for just one result of JSON and not for the 3 results which are available in Json. Also i find the var line = "" is unused any clue what might be the cause? – Kapil Soni Jun 02 '15 at 11:23
  • You can design you code in any way, to use only one string or multiple string identifiers, I just change the code to use a header string, the line string both added to the str object. The line string is added for each individual json object. To write this to a file, please follow the instructions on this post http://stackoverflow.com/questions/21012580/is-it-possible-to-write-data-to-file-using-only-javascript – faljbour Jun 02 '15 at 15:09