简体   繁体   中英

JSON pretty print customization

I'm writing a tool to modify huge json file in groovy. I read this file, add new entry and save, but I'would like to avoid changes in places I didn't touch.

I'm using new JsonBuilder( o ).toPrettyString() to get pretty formatted json output, but this function gives me result like this:

{
    "key": "Foo",
    "items": [
        {
            "Bar1": 1
        },
        {
            "Bar2": 2
        }
    ]   
}

when I need to get this:

{
    "key": "Foo",
    "items": 
    [
        {
            "Bar1": 1
        },
        {
            "Bar2": 2
        }
    ]   
} 

There should be newline before [ .

It's important to me, because in other way I cannot find in GIT history, what I really changed.

Do you have any idea how to achieve this?

The JsonBuilder method toPrettyString() delegates directly to JsonOutput.prettyPrint() as follows:

public String toPrettyString() {
    return JsonOutput.prettyPrint(toString());
}

The latter method is not really customizable at all. However, the source is freely available from any Maven central repository or mirror. I would suggest finding the source and creating your own variant of the method that behaves the way you would like it to. The source for JsonOutput.prettyPrint() is only about 65 lines long and shouldn't be that hard to change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM