如何避免json.dumps()编码已经编码的字符串?



我使用了一个模块,它接受二进制数据并将其转换为Python字典。然后将该数据解析为另一个Python字典结构。最后,我使用json.dumps()将记录转储到磁盘。

我刚刚发现这个库编码双引号,json库然后转义这些转义。

想象下面的字符串:Sean "Puff Daddy"梳子

import json
record = some_binary_file_reading_module.read()
print(record["name") # prints "Sean "Puff Daddy" Combs"
my_new_record = create_new_record(record)
myfile.write(json.dumps(my_new_record) # output becomes "Sean \"Puff Daddy\" Combs"

如何避免第二次转义?这些记录可以包含各种各样的字符串,所以我认为这个并不是唯一的逃脱。我必须自己写算法吗?

我有一个类似的例子,读取数据到csv。然后使用json.dumps

将其值序列化为json

如果模式是一致的(听起来是一致的),您可以在字符串中替换它:

my_string.replace('\"', '')

最新更新