[英]How to not escape backslash when writing to JSON
I am trying to read a JSON file and add a new key,value
pair to it.我正在尝试读取 JSON 文件并向其添加新的
key,value
对。 Then write the JSON file back.然后将 JSON 文件写回。 Example
例子
# Read the JSON and add a new K,V
input_file_path = os.path.join(os.path.dirname(__file__), 'test.json')
input_file = open(input_file_path, 'r')
data = json.load(input_file)
data['key'] = os.environ.get('KEY', '') #<-- Adding a new K,V
input_file.close()
# Write the JSON to tmp.
output_file = open('/tmp/' + 'test.json', 'w')
json.dump(data, output_file, indent=4)
output_file.close()
My input JSON looks like this我的输入 JSON 看起来像这样
{
"type": "account"
}
My env variable called KEY
looks like this -----BEGINKEY-----\\nVgIBMIIE
我的名为
KEY
变量看起来像这样-----BEGINKEY-----\\nVgIBMIIE
The final JSON file written to tmp looks like this写入 tmp 的最终 JSON 文件如下所示
{
"private_key": "-----BEGINKEY-----\\nVgIBMIIE",
"type": "account"
}
I am not able to figure out why the backslash is escaped?我无法弄清楚为什么要转义反斜杠? How can I avoid this?
我怎样才能避免这种情况?
The program is treating your input string as a raw string and so adds the extra \\
.该程序将您的输入字符串视为原始字符串,因此添加了额外的
\\
。 The original '\\' is not actually escaping anything, so for it to be represented in Python as a string, you need to escape it.原始的 '\\' 实际上并没有转义任何内容,因此要在 Python 中将其表示为字符串,您需要对其进行转义。 As you saw this can be problematic however.
然而,正如您所看到的,这可能是有问题的。 You can force the string back to unicode format using:
您可以使用以下命令将字符串强制恢复为 unicode 格式:
import codecs
raw_val = os.environ.get('KEY', '')
val = codecs.decode(raw_val, 'unicode_escape')
data['key'] = val
If you want to represent -----BEGINKEY-----\\nVgIBMIIE
in JSON, it has to go in a double quoted string.如果要在 JSON 中表示
-----BEGINKEY-----\\nVgIBMIIE
,则必须使用双引号字符串。
In double quoted strings, backslashes have special meaning.在双引号字符串中,反斜杠具有特殊含义。 It's not possible to write a backslash character simply by typing
"\\"
.不能简单地通过键入
"\\"
来编写反斜杠字符。 This would generate an error.这会产生错误。
Therefore, the backslash must be escaped.因此,必须转义反斜杠。 Hence
-----BEGINKEY-----\\nVgIBMIIE
becomes "-----BEGINKEY-----\\\\nVgIBMIIE"
in a JSON string.因此
-----BEGINKEY-----\\nVgIBMIIE
在 JSON 字符串中变为"-----BEGINKEY-----\\\\nVgIBMIIE"
。
If you want to get rid of the backslash, you need to represent如果你想去掉反斜杠,你需要代表
-----BEGINKEY-----
VgIBMIIE
rather than而不是
-----BEGINKEY-----\nVgIBMIIE
These two things are not the same thing.这两件事不是一回事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.