I'm currently trying to merge multiple .txt files into one big json file. I created a function that takes in the txt file as an argument and the json file it will write too. I'm utilizing google's simple-json package to handle creation of json objects.
The main issues I'm having is that it writes succesfully to the json file, but is not properly formatted.
For example, this is one line of the text file
{"sensor_name":"Activity","timestamp":{"start_time":"Thu Jan 5 00:00:00 EST 2017","end_time":"Thu Jan 5 07:57:33 EST 2017"},"sensor_data":{"activity":"unknown","duration":28653345}}
My approach is to loop over the file, convert each line into a JSONObject type and then write that JSONObject to the file. The code successfully writes the JSONObject to the file, but fails to format the .json properly.
Here is an example of what the .json will look like.
{"sensor_data":{"duration":41143403,"activity":"unknown"},"sensor_name":"Activity","timestamp":{"start_time":"Mon Mar 6 00:00:00 EST 2017","end_time":"Mon Mar 6 11:25:44 EST 2017"}}
{"sensor_data":{"duration":61245,"activity":"walking"},"sensor_name":"Activity","timestamp":{"start_time":"Mon Mar 6 11:25:44 EST 2017","end_time":"Mon Mar 6 11:26:45 EST 2017"}}
{
{
"sensor_data":{
"duration":41143403,
"activity":"unknown"
},
"sensor_name":"Activity",
"timestamp":{
"start_time":"Mon Mar 6 00:00:00 EST 2017",
"end_time":"Mon Mar 6 11:25:44 EST 2017"
},
},
{
"sensor_data":{
"duration":61245,
"activity":"walking"
},
"sensor_name":"Activity",
"timestamp":{
"start_time":"Mon Mar 6 11:25:44 EST 2017",
"end_time":"Mon Mar 6 11:26:45 EST 2017"
}
},
},
the important details to keep in mind is adding commas at the end of each object. The parser nor the .toString method will not handle it
/*
* method to set up a txt file as a json file
* each line in the text file is considered an object
* Args[]
* txtFile (File): text file that is not formatted in json
* fileToWriteTo (FileWriter): the file that the json will be written to
* returns
* none
* */
private void prepareForJson(File txtFile, FileWriter fileToWriteTo) {
// parser for reading strings
JSONParser parser = new JSONParser();
BufferedReader reader;
try {
reader = new BufferedReader((new FileReader(txtFile)));
String line = reader.readLine();
// convert that line to an json object
while (line != null) {
JSONObject lineConvertedToJson = (JSONObject) parser.parse(line);
// write to the file
fileToWriteTo.write(lineConvertedToJson.toJSONString());
// read the next line
line = reader.readLine();
}
} catch (Exception e){
e.getStackTrace();
}
}
Any suggestions on how to properly format txt files into json files?