4
1

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.

jQuery で、json を csv に変換してダウンロード

Last updated at Posted at 2017-07-02

参考にしたページ
jQuery だけで CSVファイル作成とダウンロードを実装する

Chrome では動くのですが、Firefox では動きません (2018-5-27 に確認)

csv_download_jul02.png

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<script src="/js/jquery-3.2.1.min.js"></script>
<script src="/js/jquery.csv.min.js"></script>
<script src="csv_download.js"></script> 
<title>CSV ダウンロード</title>
</head>
<body>
<h2>jquery.csv.min.js</h2>
<pre id="json"></pre>
<p />
<pre id="preview"></pre>
<button id="download">CSV ダウンロード</button><p />

<p />
<div id="contents"></div>
<hr />
<div id="outarea_aa">outarea_aa</div>
<div id="outarea_bb">outarea_bb</div>
<div id="outarea_cc">outarea_cc</div>
<div id="outarea_dd">outarea_dd</div>
<div id="outarea_ee">outarea_ee</div>
<div id="outarea_ff">outarea_ff</div>
<div id="outarea_gg">outarea_gg</div>
<div id="outarea_hh">outarea_hh</div>
<hr />
Jul/02/2017<p />
</body>
</html>
csv_download.js
// -------------------------------------------------------------------
//	csv_download.js
//
//					Jul/02/2017
// -------------------------------------------------------------------
jQuery (function ()
{
	jQuery("#outarea_aa").text ("*** csv_download.js *** 開始 ***")

	const json_file = "in01.json"
	const csv_file = "aaa01.csv"

	jQuery.getJSON(json_file,function (res)
	{
	jQuery('#json').text(JSON.stringify(res,undefined,4))

	const content = jQuery.csv.fromObjects(res)
	jQuery('#preview').text(content)

	jQuery("#download").click (function ()
		{
		const blob = new Blob([ content ], { "type" : "text/csv" })
		jQuery("<a></a>", {href: window.URL.createObjectURL(blob),
			download: csv_file,
			target: "_blank"})[0].click()
		})
	})

	jQuery("#outarea_hh").text ("*** csv_download.js *** 終了 ***")
})

// -------------------------------------------------------------------
in01.json
[
	{"key":"AAA","v1":"Good","v2":"Morning"},
	{"key":"BBB","v1":"Good","v2":"Afternoon"},
	{"key":"CCC","v1":"Hello","v2":"Everybody"},
	{"key":"DDD","v1":"See","v2":"you"}
]
4
1
2

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?