I have a valid JSON String that I want to tidy/format such that each property/value pair is on its own line, etc. (it currently is on one line with no spaces/line breaks).
I am using the Apache Sling JSONObject
to model my JSON Object and turn it into a String, so if the Sling JSONObject
can be set to output a tidy string (which I do not think it can) that would work too.
If I need a 3rd party lib I would prefer one with as few dependencies as possibles (such as Jackson which only requires the std JDK libs).
We can use the Python json module to pretty-print the JSON data. The json module is recommended to work with JSON files. We can use the dumps() method to get the pretty formatted JSON string.
We can pretty-print a JSON using the toString(int indentFactor) method of org. json. JSONObject class, where indentFactor is the number of spaces to add to each level of indentation.
String jsonFormattedString = jsonStr. replaceAll("\\", "");
With gson you can do:
JsonParser parser = new JsonParser(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement el = parser.parse(jsonString); jsonString = gson.toJson(el); // done
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