quinnj / JSON3.jl

Other
214 stars 47 forks source link

Left align JSON keys when using JSON3.pretty() #161

Closed mkshirazi closed 2 years ago

mkshirazi commented 3 years ago

Currently, the JSON is being aligned with :. The keys should be aligned left so all keys at a stage are in line. This will be in line with the pretty definition of JSON. In the current status, it is difficult to read JSON as it is printed.

MWE:

julia> t = """{"a":"abc","aaaaaaaaaaaaaa":{"a":"abc","aaaaaaaaaaaaaa":"abc"},"c":"abc"}""";

julia> JSON3.pretty(JSON3.read(t))
{
                "a": "abc",
   "aaaaaaaaaaaaaa": {
                        "aaaaaaaaaaaaaa": "abc",
                                     "a": "abc"
                     },
                "c": "abc"
}
julia> 
Teo-ShaoWei commented 3 years ago

I happened to be thinking strongly about opening an issue about this when I saw this!

To elaborate, I would prefer to have the following too:

julia> t = """{"a":"abc","aaaaaaaaaaaaaa":{"a":"abc","aaaaaaaaaaaaaa":"abc"},"c":"abc"}""";

julia> JSON3.pretty(JSON3.read(t))
{
    "a": "abc",
    "aaaaaaaaaaaaaa": {
        "aaaaaaaaaaaaaa": "abc",
        "a": "abc"
    },
     "c": "abc"
}

That said, I would acknowledge that prettifying might be opinionated. There are also people who would strongly prefer column-indentation. For example Golang's default formatting program gofmt does that. Heck, even the left-align indentation camp can't agree on 2-space or 4-space 😛

So I would propose that there's a way to pass in a PrettifyContext (or something better named) which represents the alignment preference, and store the current indentation/offset. The left-alignment and column-alignment contexts can either be implemented as objects of it, or concrete child structs of it.

Then the following function will take in the context instead of the indent/offset. https://github.com/quinnj/JSON3.jl/blob/1c692023cdcb9e24038276639fea2ad5a5eb879b/src/pretty.jl#L27

Within pretty, interaction with offset will be abstracted by function calls. In that case we can have the left-alignment to always set it to 0 will the column-alignment will continue to calculate it.

Thoughts?

mkshirazi commented 3 years ago

I think its a good suggestion. Gives users the option to control for what prettifying option they need

quinnj commented 3 years ago

I don't have a strong opinion here; I think I right-aligned because it was just easier to implement. If someone wants to make a PR to change things or provide option to configure things, I'd happily review.