0
3

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 1 year has passed since last update.

CSVをJSONに変換する

Last updated at Posted at 2020-04-01

CSVをJSONに変換する

ファイル不正時などはいったん考慮せず、ロジックだけおぼえがき。

csvToJson.java
	/**
	 * CSVファイルの全行をJSON形式に変換する.
	 */
	public void csvToJson() {

		// csvファイル読込
		File csv = new File("csvファイルパス");
		try (BufferedReader br = new BufferedReader(new FileReader(csv));) {

			// 先頭行はカラム名
			final String[] header = br.readLine().split(",");
			List<String> jsonRecords = new LinkedList<>();

			loop: while (true) {

				// 全行取得
				String record = br.readLine();
				if (record == null) break loop;
				String[] column = record.split(",");

				// {"header0":"column0","header1":"column1"}という形に成形
				String jsonRecord = "{" + IntStream.range(0, header.length).boxed()
						.map(v -> "\"" + header[v] + "\":\"" + column[v] + "\"")
						.collect(Collectors.joining(",")) + "}";

				jsonRecords.add(jsonRecord);
			}

			// [{"header0":"0","header1":"1"},{"header0":"2","header1":"3"}]という形に接続
			String json = "[" + String.join(",", jsonRecords) + "]";

			System.out.println(json);

		} catch (IOException e) {
		}
	}
0
3
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
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?