search
LoginSignup
61

More than 5 years have passed since last update.

posted at

updated at

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

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
61