44

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...

RajnishCoder
  • 2,429
  • 5
  • 14
  • 33
user1371896
  • 1,834
  • 7
  • 22
  • 31
  • I guess you've already checked http://stackoverflow.com/questions/4130849/convert-json-format-to-csv-format-for-ms-excel and that didn't work for you? – Ando Jun 29 '12 at 06:33

9 Answers9

27

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

Raghd Hamzeh
  • 304
  • 10
  • 16
Hemant Metalia
  • 25,838
  • 17
  • 67
  • 86
21

Here is my solution

function arrayToCSV(objArray) {
     const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
     let str = `${Object.keys(array[0]).map(value => `"${value}"`).join(",")}` + '\r\n';

     return array.reduce((str, next) => {
         str += `${Object.values(next).map(value => `"${value}"`).join(",")}` + '\r\n';
         return str;
        }, str);
 }

Example:

let arr = [{name: "Essa", age: 25}];
console.log(arrayToCSV(arr));
Eesa
  • 2,288
  • 2
  • 24
  • 46
15

Probably more elegant and the simplest solution

function convertToCSV(arr) {
  const array = [Object.keys(arr[0])].concat(arr)

  return array.map(it => {
    return Object.values(it).toString()
  }).join('\n')
}


console.log(
  convertToCSV(
    [
      {
        id: 1,
        name: 'Foo',
        timestamp: new Date()
      },
      {
        id: 2,
        name: 'Bar',
        timestamp: new Date()
      },
      {
        id: 3,
        name: 'Baz',
        timestamp: new Date()
      }
    ]
  )
)
mightybruno
  • 1,117
  • 5
  • 11
6

Here's a solution similar to mightybruno's answer that handles strings containing commas. None of the other answers seem to take this in to consideration.

function objectsToCSV(arr) {
    const array = [Object.keys(arr[0])].concat(arr)
    return array.map(row => {
        return Object.values(row).map(value => {
            return typeof value === 'string' ? JSON.stringify(value) : value
        }).toString()
    }).join('\n')
}
Mattijs
  • 71
  • 1
  • 4
1

This is my solution

https://jsfiddle.net/dhou6y3o/

function iterateObject(obj) {
  var value = '', header = '';
          for (name in obj) {
            if (obj.hasOwnProperty(name)) {
              if (isObject(obj[name])) {
                var out = iterateObject(obj[name]);
                value += out.value;
                header += out.header;
              } else {
                value += removeNewLine(obj[name]) + '; ';
                header += name + '; ';
              }
            }
          }
  return {
    "value":value,
    "header":header
  };
}
function isObject(obj) {
  return (typeof obj === 'object');
}
function removeNewLine(item) {
  return item.toString().replace(/(\r\n|\n|\r)/gm,"");
}
carlo denaro
  • 429
  • 6
  • 14
1

This is a quick & dirty, but probably works for most cases:

const headers = Object.keys(objAry[0])
console.log(headers.join())

objAry.forEach(r => console.log(
   Object.values(r)
   .map(c => Array.isArray(c)? `"${c.join()}"` : c)
   .join())
)
Jeff Lowery
  • 1,953
  • 24
  • 34
1

Use papaparse library to convert JSON to CSV and Vice Versa. Refer to this link - https://www.papaparse.com/

1

Below code will convert and download JSON array to csv as a file.

 function exportJSONToCSV(objArray) {
    var arr = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
    var str =
      `${Object.keys(arr[0])
        .map((value) => `"${value}"`)
        .join(',')}` + '\r\n';
    var csvContent = arr.reduce((st, next) => {
      st +=
        `${Object.values(next)
          .map((value) => `"${value}"`)
          .join(',')}` + '\r\n';
      return st;
    }, str);
    var element = document.createElement('a');
    element.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvContent);
    element.target = '_blank';
    element.download = 'export.csv';
    element.click();
  }
Anup Bangale
  • 341
  • 2
  • 6
0

Similar to mightybruno's answer but this would allow separate access to the headers and content (by moving the join statements to later in the function) if desired.

function objToCsv(data) {
    const headers = Object.keys(data[0]).join();
    const content = data.map(r => Object.values(r).join());
    return [headers].concat(content).join("\n");
}
SuperCodeBrah
  • 1,704
  • 2
  • 14
  • 20