Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

arrays - Converting JSON object to CSV format in JavaScript

I am trying to convert a JavaScript object set in to CSV format

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

This is how I tried to work it out... but 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 Stackoverflow was not really useful me...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 + '
';
            }

            return str;
        }

Source


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...