[英]How to dump json-like string without quoting keys?
Instead of this (from json.dumps
): 代替这个(来自
json.dumps
):
[
{
"created": 581937573,
"text": "asdf"
},
{
"created": 581937699,
"text": "asdf"
}
]
I would like to get this [non-JSON] output: 我想获得此[non-JSON]输出:
[
{
created: 581937573,
text: "asdf"
},
{
created: 581937699,
text: "asdf"
}
]
If json.dumps
had an option to change the quote character for keys, I could just set it to a placeholder and strip them out later. 如果
json.dumps
可以更改键的引号字符,则可以将其设置为占位符,然后将其剥离。 Unfortunately it doesn't appear to have this option... any other clever ideas? 不幸的是,它似乎没有这个选择……还有其他聪明的主意吗?
(load from this format is not necessary, but would be interesting if a solution for it exists as well) (从这种格式加载不是必需的,但如果也有解决方案,这将很有趣)
re.sub
offers a quick fix under certain assumptions: 在某些假设下,
re.sub
提供了快速解决方案:
import re
data = [...]
json_data = json.dumps(data)
with open('file.txt', 'w') as f:
f.write(re.sub(r'"(.*?)"(?=:)', r'\1', json_data))
file.txt
[
{
created: 581937573,
text: "asdf"
},
{
created: 581937699,
text: "asdf"
}
]
These assumptions are 这些假设是
re.sub
runs in a reasonable amount of time re.sub
可以在合理的时间内运行 The pattern effectively looks for all dictionary keys and strips out the quotes. 该模式有效地查找了所有字典键并去除了引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.