Skip to content

Commit 23f3f3e

Browse files
committed
Escaping special characters in the json output
1 parent 4b297c8 commit 23f3f3e

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

test/Test.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,18 @@
55
import java.util.TreeMap;
66
import java.util.concurrent.atomic.AtomicInteger;
77

8+
/**
9+
* Read properties and sort by key so it can be compared with the Python jprops output
10+
* Format output as valid JSON (escape quotes) to match the json output from Python dict
11+
*/
812
public class Test {
13+
public static String jsonEscape(String value) {
14+
String escaped = value;
15+
escaped = escaped.replaceAll("\"", "\\\\\"");
16+
escaped = escaped.replaceAll("\t", "\\\\t");
17+
escaped = escaped.replaceAll("\f", "\\\\f");
18+
return escaped;
19+
}
920
public static void main(String[] args) {
1021
try (InputStream inputStream = new FileInputStream("test.properties")) {
1122
Properties properties = new Properties();
@@ -14,7 +25,8 @@ public static void main(String[] args) {
1425
properties.forEach((key, value) -> orderedProperties.put((String) key, (String) value));
1526
System.out.println("{");
1627
final AtomicInteger counter = new AtomicInteger(1);
17-
orderedProperties.forEach((key, value) -> System.out.format(" \"%s\": \"%s\"%s%n", key, value,
28+
orderedProperties.forEach((key, value) -> System.out.format(" \"%s\": \"%s\"%s%n",
29+
jsonEscape(key), jsonEscape(value),
1830
(counter.getAndIncrement() == orderedProperties.size()) ? "" : ", "));
1931
System.out.println("}");
2032
} catch (IOException e) {

0 commit comments

Comments
 (0)