Converting JSON object to CSV format in JavaScript

前端 未结 9 707
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 04:37

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

相关标签:
9条回答
  • 2020-11-30 04:59

    Probably more elegant and the simplest solution, plain javascript in 4 lines of code (tho it works only for flat objects, i.e. no arrays inside)

    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()
          }
        ]
      )
    )

    Edit. Some explanation:

    First lets have a look on [Object.keys(arr[0])]

    If you do Object.keys({ foo: 123 }) you'll get another object (an array) which is represented like that: { 0: "foo" }. If we place both of these objects in an array we will have

    [
      { 0: "foo" },
      { foo: 123 }
    ]
    

    which is being done with .concat(arr).

    Now, as you can see, if we take just the values of everything we have in the array, we will get a valid CSV where each row is represented by an entry in the array. It's exactly what this part does:

          return array.map(it => {
            return Object.values(it).toString()
          }).join('\n')
    
    0 讨论(0)
  • 2020-11-30 05:08

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

    0 讨论(0)
  • 2020-11-30 05:09

    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,"");
    }
    
    0 讨论(0)
  • 2020-11-30 05:10

    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

    0 讨论(0)
  • 2020-11-30 05:12

    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));
    
    0 讨论(0)
  • 2020-11-30 05:16

    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");
    }
    
    0 讨论(0)
提交回复
热议问题