简体   繁体   中英

How to selectively prettify certain elements of json in python

How is it possible to selectively prettify json files in python based on the key. For example, although i want it generally prettified, i want dictionaries under the key "DATE" to collapse to a single line to conserve space.

{
 "String_entered": "string",
 "DATE": {
    "year":2013,
    "month":null,
    "day":null
   },
}

To:

{
 "String_entered": "string",
 "DATE": {"year":2013,"month":null,"day":null},
}

A slightly hacky solution would be to pop that key and then append it on afterwards:

def pretty_avoid(d, k, t):
    v = d.pop(k)
    print(json.dumps(d,indent=t)[:-1]+' '*t+'"'+k+'": '+json.dumps(v)+'\n}')

which produces the expected output (with d as the dict):

>>> pretty_avoid(d, 'DATE', 4)
{
    "String_entered": "string"
    "DATE": {"year": 2013, "month": null, "day": null}
}

Note that this does modify the input dictionary which may not be a problem for you, but if it were, you could use copy.deepcopy .

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