-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonToCSV.java
More file actions
76 lines (57 loc) · 2.36 KB
/
Copy pathJsonToCSV.java
File metadata and controls
76 lines (57 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import com.opencsv.CSVWriter;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class JsonToCSV {
public static void main(String filePath) {
Path pathToFile = Paths.get(filePath);// filePath is the path to json file
//instance of BufferedReader to read the file
try (BufferedReader bufferedReader = Files.newBufferedReader(pathToFile,
StandardCharsets.US_ASCII)) {
//read a new line
String line = bufferedReader.readLine();
List<String[]> listArrayList = new ArrayList<>();
//Suppose the dataset in relaxed json is such a format :
// {"category" : ... , "headline": ... , "date":...}
// {"category" : ... , "headline": ... , "date":...} and so on.
while (line != null) {
line = line.replaceAll("\\{", "")
.replaceAll("}", "")
.replaceAll("category", "")
.replaceAll("\"", "")
.replaceAll(": ", "")
.replaceAll(", headline", ",\t")
.replaceAll(", date", ",\t");
String[] attributes = line.split(",\t");
listArrayList.add(attributes);
line = bufferedReader.readLine();
}
File file = new File(pathToCSV);
try {
//create a file writer
FileWriter fileWriter = new FileWriter(file);
//create csv writer obj
CSVWriter csvWriter = new CSVWriter(fileWriter);
//adding header to csv
String[] header = {"CATEGORY", "HEADLINE", "DATE"};
csvWriter.writeNext(header);
//add data to csv
csvWriter.writeAll(listArrayList);
//close writer
csvWriter.close();
} catch (Exception e) {
System.out.println("the exception is " + e);
}
} catch (Exception e) {
System.out.println("here is the exception");
e.printStackTrace();
}
}
}