我有一个类似的问题this previous question 。但是,我的字典具有如下结构
data_dict = {
'refresh_count': 1,
'fetch_date': '10-10-2019',
'modified_date': '',
'data': [
{'date': '10-10-2019', 'title': 'Hello1'},
{'date': '11-10-2019', 'title': 'Hello2'}
]
}
我想将其存储在 JSON 中,以便我的数据仍然存储在每行一个字典中。像这样的东西:
{
'refresh_count': 1,
'fetch_date': '10-10-2019',
'modified_date': '',
'data': [
{'date': '10-10-2019', 'title': 'Hello1'},
{'date': '11-10-2019', 'title': 'Hello2'}
]
}
我无法仅使用 json.dumps
(或 dump
)或以前的解决方案来实现它。
json.dumps(data_dict, indent=2)
>> {
"refresh_count": 1,
"fetch_date": "10-10-2019",
"modified_date": "",
"data": [
{
"date": "10-10-2019",
"title": "Hello1"
},
{
"date": "11-10-2019",
"title": "Hello2"
}
]
}
最佳答案
这确实是一个 hack,但是您可以实现一个自定义 JSON 编码器来执行您想要的操作(请参阅 Custom JSON Encoder in Python With Precomputed Literal JSON )。对于任何您不想缩进的对象,请用 NoIndent
将其包裹起来。类(class)。自定义 JSON 编码器将在 default()
中查找此类型。方法并返回唯一字符串 ( __N__
) 并将未缩进的 JSON 存储在 self._literal
中。随后,在调用encode()
时,这些唯一的字符串将被替换为不缩进的 JSON。
请注意,您需要选择不可能出现在编码数据中的字符串格式,以避免无意中替换某些内容。
import json
class NoIndent:
def __init__(self, o):
self.o = o
class MyEncoder(json.JSONEncoder):
def __init__(self, *args, **kwargs):
super(MyEncoder, self).__init__(*args, **kwargs)
self._literal = []
def default(self, o):
if isinstance(o, NoIndent):
i = len(self._literal)
self._literal.append(json.dumps(o.o))
return '__%d__' % i
else:
return super(MyEncoder, self).default(o)
def encode(self, o):
s = super(MyEncoder, self).encode(o)
for i, literal in enumerate(self._literal):
s = s.replace('"__%d__"' % i, literal)
return s
data_dict = {
'refresh_count': 1,
'fetch_date': '10-10-2019',
'modified_date': '',
'data': [
NoIndent({'date': '10-10-2019', 'title': 'Hello1'}),
NoIndent({'date': '11-10-2019', 'title': 'Hello2'}),
]
}
s = json.dumps(data_dict, indent=2, cls=MyEncoder)
print(s)
super(MyEncoder, self).encode(o)
返回的中间表示:
{
"fetch_date": "10-10-2019",
"refresh_count": 1,
"data": [
"__0__",
"__1__"
],
"modified_date": ""
}
最终输出:
{
"fetch_date": "10-10-2019",
"refresh_count": 1,
"data": [
{"date": "10-10-2019", "title": "Hello1"},
{"date": "11-10-2019", "title": "Hello2"}
],
"modified_date": ""
}
关于python - 将键的字典和键内的字典列表保存到 JSON,其中字典按行存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58327845/