Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert pretty format json file into a simple single line json file using java?

Tags:

java

json

string

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"}]'
like image 297
Uncle Sam Avatar asked Feb 17 '21 08:02

Uncle Sam


2 Answers

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"   }]
like image 151
Harshal Parekh Avatar answered Sep 21 '22 12:09

Harshal Parekh


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);
like image 44
Domenico Sibilio Avatar answered Sep 18 '22 12:09

Domenico Sibilio