[英]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. 如何基于密钥有选择地在python中美化json文件。 For example, although i want it generally prettified, i want dictionaries under the key "DATE" to collapse to a single line to conserve space.
例如,尽管我希望它通常被美化,但我希望键“ DATE”下的字典折叠成一行以节省空间。
{
"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): 产生预期的输出(以
d
为字典):
>>> 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
. 请注意,这确实会修改输入字典,这对您来说可能不是问题,但如果是这样,则可以使用
copy.deepcopy
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.