I need to conver Pretty format json file into a single line json file. But unable to do so. Can anyone help me on this?
Example: the below needs to be converted
[
 {
  "Employee ID": 1,
  "Name": "Abhishek",
  "Designation": "Software Engineer"
 },
 {
  "Employee ID": 2,
  "Name": "Garima",
  "Designation": "Email Marketing Specialist"
 }
]
[
   {
      "Employee ID": 1,
      "Name": "Abhishek",
      "Designation": "Software Engineer"
   },
   {
      "Employee ID": 2,
      "Name": "Garima",
      "Designation": "Email Marketing Specialist"
   }
]
to this:
 '[{"Employee ID":1,"Name":"Abhishek","Designation":"Software Engineer"},' \ 
            '{"Employee ID":2,"Name":"Garima","Designation":"Email Marketing Specialist"}]'
                A better and more complete version of this answer with proper error handling and removal of extra spaces.
One problem of the referred answer is that it uses .concat() without .trim() - a very deeply nested pretty-JSON's indents will be visible as extra spaces in final output.
String unprettyJSON = null;
try {
    unprettyJSON = Files.readAllLines(Paths.get("pretty.json"))
                        .stream()
                        .map(String::trim)
                        .reduce(String::concat)
                        .orElseThrow(FileNotFoundException::new);
} catch (IOException e) {
    e.printStackTrace();
}
Output with trim:
[{"Employee ID": 1,"Name": "Abhishek","Designation": "Software Engineer"},{"Employee ID": 2,"Name": "Garima","Designation": "Email Marketing Specialist"}][{"Employee ID": 1,"Name": "Abhishek","Designation": "Software Engineer"},{"Employee ID": 2,"Name": "Garima","Designation": "Email Marketing Specialist"}]
Output without trim:
[ {  "Employee ID": 1,  "Name": "Abhishek",  "Designation": "Software Engineer" }, {  "Employee ID": 2,  "Name": "Garima",  "Designation": "Email Marketing Specialist" }][   {      "Employee ID": 1,      "Name": "Abhishek",      "Designation": "Software Engineer"   },   {      "Employee ID": 2,      "Name": "Garima",      "Designation": "Email Marketing Specialist"   }]
                        If you read the file contents via Files.readAllLines(Path) then you already get each line as a different item in a list, which you can in turn merge together into a single line.
For example:
String oneLine = Files.readAllLines(Paths.get("input.json"))
.stream()
.reduce(String::concat)
.orElseThrow();
System.out.println(oneLine);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With