Tombart Tombart - 29 days ago 9
Java Question

Escape JSON string in Java

I'm using Google's

com.google.api.client.json.GenericJson
and
com.fasterxml.jackson.core.JsonGenerator
. I would like to serialize JSON object and escape quotes and backslashes so that I can pass that string in Bash. And afterwards deserialize that string.

GenericJson.toString
produces simple JSON, but
\n
etc. are not escaped:

{commands=ls -laF\ndu -h, id=0, timeout=0}


is there a simple way how to get something like this:

"{commands=\"ls -laF\\ndu -h\", id=0, timeout=0}"


I don't want to reinvent the wheel, so I'd like to use Jackson or an existing API, if possible.

Answer

An easy way to escape a string so it can be processed in bash scripts, is to single-quote the whole string (in bash everything inside single quotes is taken as its literal value, newlines included, except, of course, the single quotes)

The only character that would need to be quoted would be any possible single quote inside the json string itself (to escape it yo need to replace from ' to '\'') in this way:

String jsonString = getJsonStringFromSomewhere();

// jsonString now have a value suitable for bash
jsonString = "'" + jsonString.replaceAll("'", "'\\\\''") + "'";

As a proof of concept, try with the following example:

String jsonString = "{\"uno\": 1, \"dos\": \"this is a simple quote: ', and this is an 'n' followed by a slash (escape for a new line in json): \\n \"}";
jsonString = "'" + jsonString.replaceAll("'", "'\\\\''") + "'";
System.out.println("echo " + jsonString);

Then copy/paste the resulting "bash command" "echo " in your terminal and execute it, it must print the JSON string:

{"uno": 1, "dos": "this is a simple quote: ', and this is an 'n' followed by a slash (escape for a new line in json): \n "}
Comments