【发布时间】:2020-03-03 07:57:00
【问题描述】:
我想重新格式化一个 JSON 文件,以便具有某些特定键的某些对象(字典)在一行上。
例如,任何带有 name 键的对象都应该出现在一行中:
{
"this": "that",
"parameters": [
{ "name": "param1", "type": "string" },
{ "name": "param2" },
{ "name": "param3", "default": "@someValue" }
]
}
生成 JSON 文件,其中包含编程语言数据。单行的某些字段使目视检查/审查变得更加容易。
在写入之前,我尝试覆盖 python json.JSONEncoder 以将匹配的 dict 转换为 string,只是为了实现字符串中的引号 " 在结果 JSON 文件中再次转义,这违背了我的目的。
我还查看了jq,但无法找到解决方法。我根据行长找到了类似的问题和解决方案,但是我的要求更简单,我不希望更改其他较短的行。仅限某些对象或字段。
【问题讨论】:
-
json.dumps(parsed, indent=4, sort_keys=True) 够漂亮吗?
-
覆盖
json.JSONEncoder会起作用。建议您尝试提出问题,因为您遇到的任何问题都可能得到解决。另请参阅我对How to implement custom indentation when pretty-printing with the JSON module? 的回答
标签: python json jq pretty-print