作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想将 Python 字典转储到具有特定自定义格式的 JSON 文件中。比如下面的字典my_dict
,
'text_lines': [{"line1"}, {"line2"}]
倾倒了
f.write(json.dumps(my_dict, sort_keys=True, indent=2))
看起来像这样
"text_lines": [
{
"line1"
},
{
"line2"
}
]
虽然我更喜欢它看起来像这样
"text_lines":
[
{"line1"},
{"line2"}
]
同样的,我想要下面的
"location": [
22,
-8
]
看起来像这样
"location": [22, -8]
(也就是说,更像是一个坐标,它就是)。
我知道这是一个表面问题,但保留此格式以便于手动编辑文件对我来说很重要。
有什么方法可以进行这种定制?一个解释过的例子会很棒(文档并没有让我走得太远)。
最佳答案
我使用了 Tim Ludwinski 提供的示例并根据我的喜好对其进行了调整:
class CompactJSONEncoder(json.JSONEncoder):
"""A JSON Encoder that puts small lists on single lines."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.indentation_level = 0
def encode(self, o):
"""Encode JSON object *o* with respect to single line lists."""
if isinstance(o, (list, tuple)):
if self._is_single_line_list(o):
return "[" + ", ".join(json.dumps(el) for el in o) + "]"
else:
self.indentation_level += 1
output = [self.indent_str + self.encode(el) for el in o]
self.indentation_level -= 1
return "[\n" + ",\n".join(output) + "\n" + self.indent_str + "]"
elif isinstance(o, dict):
self.indentation_level += 1
output = [self.indent_str + f"{json.dumps(k)}: {self.encode(v)}" for k, v in o.items()]
self.indentation_level -= 1
return "{\n" + ",\n".join(output) + "\n" + self.indent_str + "}"
else:
return json.dumps(o)
def _is_single_line_list(self, o):
if isinstance(o, (list, tuple)):
return not any(isinstance(el, (list, tuple, dict)) for el in o)\
and len(o) <= 2\
and len(str(o)) - 2 <= 60
@property
def indent_str(self) -> str:
return " " * self.indentation_level * self.indent
def iterencode(self, o, **kwargs):
"""Required to also work with `json.dump`."""
return self.encode(o)
关于python - JSON 转储自定义格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16264515/
我正在为我的应用程序使用 Tank-Auth。我唯一的问题是激活和重置帐户密码。 用于登录、注册、注销;我对这些代码没有问题; $route['login'] = "/auth/login"; $ro
我是一名优秀的程序员,十分优秀!