Skip to content

Commit

Permalink
Better JSON output formatting and testing (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
trobro authored Oct 14, 2023
1 parent 02d5796 commit dd8dad4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 16 deletions.
15 changes: 5 additions & 10 deletions src/main/org/hjson/JsonWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ public void save(JsonValue value, Writer tw, int level) throws IOException {
switch (value.getType()) {
case OBJECT:
JsonObject obj=value.asObject();
if (obj.size()>0) nl(tw, level);
tw.write('{');
for (JsonObject.Member pair : obj) {
if (following) tw.write(",");
Expand All @@ -56,8 +55,7 @@ public void save(JsonValue value, Writer tw, int level) throws IOException {
tw.write("\":");
//save(, tw, level+1, " ", false);
JsonValue v=pair.getValue();
JsonType vType=v.getType();
if (format && vType!=JsonType.ARRAY && vType!=JsonType.OBJECT) tw.write(" ");
if (format) tw.write(" ");
if (v==null) tw.write("null");
else save(v, tw, level+1);
following=true;
Expand All @@ -68,17 +66,14 @@ public void save(JsonValue value, Writer tw, int level) throws IOException {
case ARRAY:
JsonArray arr=value.asArray();
int n=arr.size();
if (n>0) nl(tw, level);
tw.write('[');
for (int i=0; i<n; i++) {
if (following) tw.write(",");
if (i > 0) tw.write(",");
JsonValue v=arr.get(i);
JsonType vType=v.getType();
if (vType!=JsonType.ARRAY && vType!=JsonType.OBJECT) nl(tw, level+1);
save(v, tw, level+1);
following=true;
nl(tw, level+1);
save(arr.get(i), tw, level+1);
}
if (following) nl(tw, level);
if (n > 0) nl(tw, level);
tw.write(']');
break;
case BOOLEAN:
Expand Down
9 changes: 3 additions & 6 deletions src/test/org/hjson/test/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,13 @@ private static boolean test(String name, String file, boolean inputCr, boolean o
String data1=data.toString(Stringify.FORMATTED);
String hjson1=data.toString(Stringify.HJSON);
if (!shouldFail) {
JsonValue result=JsonValue.readJSON(load(name+"_result.json", inputCr));
String json2 = load(name+"_result.json", outputCr);
JsonValue result=JsonValue.readJSON(json2);
String data2=result.toString(Stringify.FORMATTED);
String hjson2=load(name+"_result.hjson", outputCr);
if (!data1.equals(data2)) return failErr(name, "parse", data1, data2);
if (!hjson1.equals(hjson2)) return failErr(name, "stringify", hjson1, hjson2);

if (isJson) {
String json1=data.toString(), json2=JsonValue.readHjson(text, opt).toString();
if (!json1.equals(json2)) return failErr(name, "json chk", json1, json2);
}
if (!data1.equals(json2)) return failErr(name, "JSON stringify", data1, json2);
}
else return failErr(name, "should fail", null, null);
}
Expand Down

0 comments on commit dd8dad4

Please sign in to comment.