5
4

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.

File APIでJSONを取得、オブジェクトに変換してブラウザに表示する

Last updated at Posted at 2018-04-30

JSONファイルをJavascript用にオブジェクト化してみました。
key、value毎に表示したり、for inを利用して両方一緒に表示したりできました。

複雑で読みづらいJSON形式ファイルでも、これを通せば見やすくなりました。

そういえばMIMEをtext/jsonだと思っていたらapp...だったんですね。

html
<!DOCTYPE html>
<html>
<body>
	<form method="post" enctype="multipart/form-data">
		<input type="file" id="file" accept="application/json">
	</form>
	<p id='name'></p>
	<p id='value'></p>
	<p id='name_value'></p>
	<script>


	</script>
</body>
</html>
javascript
window.onload = function() {
	const reader = new FileReader();
	//HTMLを初期化し、新たなファイルを文字列として読込む		
	file.addEventListener('change', function(e) {
		reader.readAsText(e.target.files[0]);
		name.innerHTML = value.innerHTML = name_value.innerHTML = "";
	});
    //ファイルをオブジェクト化して表示
	reader.onload = function(e) {
		var obj = JSON.parse(e.target.result);
		for (var i = 0; i < Object.keys(obj).length; i++) {
			name.innerHTML += Object.keys(obj)[i] + '<br>';
		}
		for (var i = 0; i < Object.values(obj).length; i++) {
			value.innerHTML += Object.values(obj)[i] + '<br>';
		}
		for (key in obj) {
			name_value.innerHTML += key + ' ' + obj[key] + '<br>';
		}
	};
};
5
4
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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?