Updated
Rather than add more configuration, we plan to alter the whitespace in the JSON output to be more consistent with other libraries. In particular:
- Omit space before ":"
- Omit space after "{" and before "}"
- Add newline/indent after each array element when indent is enabled
Original
I have been using BSON for a while now for the simple fact that it is easy to get either simple plain text or a small binary format which comes in handy when you need to have both human readable/editable configs and small on disk files or over network transfers.
However when writing out formatted JSON it is useful to be able to replicate formats used by other libraries to prevent excess changes caused purely by formatting due to something like the JSON being exported from a different library/tool.
I have put some examples of JSON output from a couple of the popular libraries I could think of at the end of the description.
My proposal is that a couple of very basic settings are added to allow for some flexibility when it comes to the format of the JSON output by StrictCharacterStreamJsonWriter.
I have the code changes done in a fork of the repo and is ready for pull request which I will submit after this ticket.
The changes are fully backwards compatible and do not change the default behaviour from the current.
Example JSON outputs:
Library | Code | Output |
---|---|---|
JavaScript, NodeJS, ECMAScript [1] |
let doc = { "arr": [ { "a": 1, "b": 2 }, { "c": 3, "d": 4 } ] }; JSON.stringify(doc, null, 2) |
{ "arr": [ { "a": 1, "b": 2 }, { "c": 3, "d": 4 } ] } |
serde_json (Rust) [2] |
let doc = json!({ "arr": [ { "a": 1, "b": 2 }, { "c": 3, "d": 4 } ] }); serde_json::to_string_pretty(&doc)
|
{ "arr": [ { "a": 1, "b": 2 }, { "c": 3, "d": 4 } ] }
|
Gson | JsonObject obj1 = new JsonObject(); obj1.addProperty("a", 1); obj1.addProperty("b", 2); JsonObject obj2 = new JsonObject(); obj2.addProperty("c", 3); obj2.addProperty("d", 4); JsonArray arr = new JsonArray(); arr.add(obj1); arr.add(obj2); JsonObject doc = new JsonObject(); doc.add("arr", arr); Gson gson = new GsonBuilder() .setPrettyPrinting() .create(); String str = gson.toJson(doc); |
{ "arr": [ { "a": 1, "b": 2 }, { "c": 3, "d": 4 } ] } |
org.bson.json | BsonArray arr = new BsonArray(); arr.add(new BsonDocument() .append("a", new BsonInt32(1)) .append("b", new BsonInt32(2))); arr.add(new BsonDocument() .append("c", new BsonInt32(3)) .append("d", new BsonInt32(4))); BsonDocument doc = new BsonDocument() .append("arr", arr); var settings = JsonWriterSettings.builder() .indent(true).build(); String str = doc.toJson(settings); |
{ "arr" : [{ "a" : 1, "b" : 2 }, { "c" : 3, "d" : 4 }] } |
[1] https://jsfiddle.net/4cjd2eqx/
[2] https://play.rust-lang.org/?gist=5a05fffd61b372c906f40db3ef3859a0
- links to