1
2

More than 1 year has passed since last update.

JSONをCSVに変換する

Last updated at Posted at 2020-04-01

JSONをCSVに変換する

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

jsonToCsv.java
	/**
	 * JSONをCSVに変換する.
	 *
	 * @throws IOException
	 */
	public static void jsonToCsv() throws IOException {

		String json = "[{\"head1\":\"a\",\"head2\":\"b\",\"head3\":\"c\",\"head4\":\"d\",\"head5\":\"e\"},{\"head1\":\"1\",\"head2\":\"2\",\"head3\":\"3\",\"head4\":\"4\",\"head5\":\"5\"},{\"head1\":\"q\",\"head2\":\"qq\",\"head3\":\"qqq\",\"head4\":\"qqqq\",\"head5\":\"qqqqq\"}]";
		// 両サイドの[]を排除し、},{で区切る イメージは "head1":"1","head2":"2","head3":"3","head4":"4","head5":"5"
		List<String> trimJson = Arrays.asList(json.split("\\[")[1].split("\\]")[0].split("\\},\\{"));

		// 1レコード1mapに成形する
		Function<String, Map<String, String>> toMap = str -> {
			Map<String, String> map = new HashMap<>();
			for (String s : str.split(",")) {
				String[] keyValue = s.split(":");
				map.put(keyValue[0].split("\"")[1], keyValue[1].split("\"")[1]);
			}
			return map;
		};

		List<Map<String, String>> recordList = trimJson.stream()
				.map(String::trim)
				.map(v -> v.startsWith("\\{") ? v.split("\\{")[1] : v)
				.map(toMap)
				.collect(Collectors.toList());

		// csvファイルを作成、書き込む
		File csv = new File("csvファイルパス");
		csv.createNewFile();
		FileWriter filewriter = new FileWriter(csv);
		String header = String.join(",", recordList.get(0).keySet());
		String bodies = recordList.stream()
				.map(Map::values)
				.map(v -> String.join(",", v))
				.collect(Collectors.joining("\r\n"));
		filewriter.write(header + "\r\n");
		filewriter.write(bodies);
		filewriter.close();
	}
1
2
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
1
2