如何重新排列CSV / JSON密钥列? (JavaScript)的

时间:2015-06-23 03:04:22

标签: javascript json csv papaparse

我正在使用Papa Parse JavaScript Library将JSON对象数组转换为CSV。有没有办法让CSV列以某种方式排列。

例如;我把列作为:

OrderStatus,canOp,OpDesc,ID,OrderNumber,FinishTime,UOM,StartTime

但希望安排为:

ID,OrderNumber,OrderStatus,StartTime,FinishTime,canOp,OpDesc,UOM

我将CSV设置为未安排的原因是因为JSON数据如下所示:

json = [
{
    OrderStatus: "Good",
    canOp:"True",
    OpDesc:"Good to go",
    ID:"100",
    OrderNumber:"1000101",
    FinishTime:"20:50",
    UOM:"K",
    StartTime:"18:10"
},
...
]

由于

2 个答案:

答案 0 :(得分:1)

Papa Parse允许指定unparse()函数中的字段顺序:

var csv = Papa.unparse({
  fields: ["ID", "OrderNumber", "OrderStatus", "StartTime", "FinishTime", "canOp", "OpDesc", "UOM"],
  data: [{
      OrderStatus: "Good",
      canOp: "True",
      OpDesc: "Good to go",
      ID: "100",
      OrderNumber: "1000101",
      FinishTime: "20:50",
      UOM: "K",
      StartTime: "18:10"
    },
    // ...
  ]
});

console.log(csv);
<script src="https://unpkg.com/papaparse@4.6.3/papaparse.min.js"></script>
<h3>See your dev console for the results</h3>

答案 1 :(得分:1)

您不需要任何框架将json转换为csv。

// fields in the order you want them
var fields = ['ID', 'OrderNumber', 'OrderStatus', 'StartTime', 'FinishTime', 'canOp', 'OpDesc', 'UOM'];
var csv = json.map(function(row){
  return fields.map(function(fieldName){
    return '"' + row[fieldName]+ '"';
  });
});
csv.unshift(fields); // add header column

console.log(csv.join('\r\n'));

输出:

ID,OrderNumber,OrderStatus,StartTime,FinishTime,canOp,OpDesc,UOM
"100","1000101","Good","18:10","20:50","True","Good to go","K"
"100","1000101","Good","18:10","20:50","True","Good to go","K"