Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/**
* License : Apache License 2.0
*
* @author Michael Bornholdt Nielsen mni@jarry.dk
*
*/
public class PrettyPrintedJson {
public static void main(String[] args) {
try {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"error\": \"Expected a ',' or '}' at 15 [character 16 line 1]\",");
sb.append("\"object_or_array\": \"object\",");
sb.append("\"error_info\": \"This error came from the org.json reference parser.\",");
sb.append("\"validate\": false");
sb.append("}");
String jsonStringNoWhitespace = sb.toString();
System.out.println(" ..:: jsonStringNoWhitespace ::..");
System.out.println(jsonStringNoWhitespace);
System.out.println("");
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine scriptEngine = manager.getEngineByName("nashorn");
scriptEngine.put("jsonString", jsonStringNoWhitespace);
scriptEngine.eval("result = JSON.stringify(JSON.parse(jsonString), null, 3)");
String prettyPrintedJson = (String) scriptEngine.get("result");
System.out.println(" ..:: prettyPrintedJson ::..");
System.out.println(prettyPrintedJson);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.