在 JavaScript 中将 JSON 对象转换为 CSV 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11257062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:10:03  来源:igfitidea点击:

Converting JSON object to CSV format in JavaScript

javascriptarraysjsoncsv

提问by user1371896

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

我正在尝试将 JavaScript 对象集转换为 CSV 格式

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

你可以了解我的 Javascript 对象,如果你把它放在在线 JSON 解析器http://json.parser.online.fr/

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

这就是我试图解决它的方式......但它失败了...... 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

我正在尝试将与值“term”和相应标题相对应的整个值转换为 CSV 格式

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

是否可以在 Excel 表格中下载 csv 文件,我在 Stackoverflow 中找到的那个文件对我来说并不是真的有用...

回答by Hemant Metalia

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

和一个函数 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

来源

回答by Eesa

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));

回答by mightybruno

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

回答by Jeff Lowery

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

回答by carlo denaro

This is my solution

这是我的解决方案

https://jsfiddle.net/dhou6y3o/

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,"");
}