gpt4 book ai didi

python - JSON 转储自定义格式

转载 作者:太空狗 更新时间:2023-10-29 17:08:00 27 4
gpt4 key购买 nike

我想将 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)

另见 version I have in use .

关于python - JSON 转储自定义格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16264515/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com