Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to convert a javascript object set in to csv format

You can get the idea abt my Javascript object, if you put it in online JSON parser http://json.parser.online.fr/

This is how I tried to wrk it out... bt it flopped.. http://jsfiddle.net/fHQzC/11/

I am trying to take the whole values corresponding to the value "term" and corresponding title in to csv format

The expected output for is like

Time,Dec 9, 2012 
News,Germany,election, Egypt,Revolution, Japan, Earthquake
Person,Obama, Beckham
Title,Pearce Snubs Beckham                                
Time,Dec 5, Birthday
Person, Lebron James
News,Italy,Euro 2012 Final

Title-Heats National Champions

and is it possible to download the csv file in excel sheet the one I found in stack was nt really useful...

share|improve this question
    
I guess you've already checked stackoverflow.com/questions/4130849/… and that didn't work for you? –  Ando Jun 29 '12 at 6:33
    
yes I have...bt it did nt.. –  user1371896 Jun 29 '12 at 6:34

1 Answer 1

you can try as

$(document).ready(function () {

        // Create Object
        var items = [
              { name: "Item 1", color: "Green", size: "X-Large" },
              { name: "Item 2", color: "Green", size: "X-Large" },
              { name: "Item 3", color: "Green", size: "X-Large" }];

        // Convert Object to JSON
        var jsonObject = JSON.stringify(items);

        // Display JSON
        $('#json').text(jsonObject);

        // Convert JSON to CSV & Display CSV
        $('#csv').text(ConvertToCSV(jsonObject));
    });

and a function ConvertToCSV

// JSON to CSV Converter
        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;
        }

Source

share|improve this answer
    
my json is a bit more complex than this one.. –  user1371896 Jun 29 '12 at 6:35
    
complexity does not affect this as the format of the csv will always remain same.. –  Hemant Metalia Jun 29 '12 at 6:38
    
Ive already tried this one... I found this one on stack earlier.. –  user1371896 Jun 29 '12 at 6:39
1  
have you checked stackoverflow.com/questions/4130849/… ? –  Hemant Metalia Jun 29 '12 at 6:39
    
also refer json.org/js.html –  Hemant Metalia Jun 29 '12 at 6:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.