68
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-07-17

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
68
61
0

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
  3. You can use dark theme
What you can do with signing up
68
61

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?