写入JSON时如何不转义反斜杠

是的

我正在尝试读取JSON文件并向其中添加新的key,value对。然后写回JSON文件。

# 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()

我输入的JSON看起来像这样

{
  "type": "account"
}

我的env变量KEY看起来像这样-----BEGINKEY-----\nVgIBMIIE

写入tmp的最终JSON文件如下所示

{
  "private_key": "-----BEGINKEY-----\\nVgIBMIIE",
  "type": "account"
}

我无法弄清楚为什么反斜杠被转义了?如何避免这种情况?

Akaisteph7

该程序将您的输入字符串视为原始字符串,因此添加了多余的\原始的'\'实际上没有转义任何内容,因此要使其在Python中表示为字符串,您需要对其进行转义。如您所见,这可能会出现问题。您可以使用以下命令将字符串强制恢复为unicode格式:

import codecs

raw_val = os.environ.get('KEY', '')
val = codecs.decode(raw_val, 'unicode_escape')
data['key'] = val

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章