jsonをcsv(カンマ区切り、項目行あり)に変換する

More than 3 years have passed since last update.

textareaなどに、JSONの内容をcsvで吐き出したいときなんかに使う。


js

function json2csv(json) {

var header = Object.keys(json[0]).join(',') + "\n";

var body = json.map(function(d){
return Object.keys(d).map(function(key) {
return d[key];
}).join(',');
}).join("\n");

return header + body;
}



js

var a = [

{id:1, name:"test", address:"tokyo"},
{id:2, name:"hoge", address:"osaka"},
{id:3, name:"hello", address:"kyoto"},
{id:4, name:"world", address:"saitama"}
];

json2csv(a)

//output
id,name,address
1,test,tokyo
2,hoge,osaka
3,hello,kyoto
4,world,saitama