[英]Python (json.load) to set value to a string missing escape characters
[英]Python: Preventing json.load(file) from stripping escape characters
我正在从外部json文件中将一些数据加载到Python中,这在大多数情况下都可以正常工作。 但是,有时某些数据包含转义字符,我需要保留这些字符。
{
"version": 1,
"query": "occasionally I \"need\" to escape \"double\" quotes"
}
import json
with open('input_file', 'r') as f:
file = json.load(f)
抱歉,我应该更清楚。 我正在尝试做的事情如下:
'{}'.format(file['query'])
actual_query = '"datadog.agent.up".over("role:dns").by("host").last(1).count_by_status()'
json.dumps(actual_query)
'"\\"datadog.agent.up\\".over(\\"role:dns\\").by(\\"host\\").last(1).count_by_status()"'
这正是您应该期望的,而且我不确定为什么它不是您想要的。 请记住, print
命令返回变量的表示形式,例如print('\\"')
给出了"
。
使用示例,您可以看到输出结果时如何重新获得转义符:
import json
a = r"""{
"version": 1,
"query": "occasionally I \"need\" to escape \"double\" quotes"
}"""
j = json.loads(a)
print j
print json.dumps(j)
这给了我:
{u'query': u'occasionally I "need" to escape "double" quotes', u'version': 1}
{"query": "occasionally I \"need\" to escape \"double\" quotes", "version": 1}
(如果您能原谅python2)
回应您的编辑:
'{}'.format(file['query']) == file['query']
返回True
您正在将字符串对象格式化为字符串。 如我所建议,使用
json.dumps(file['query'])
退货
"occasionally I \"need\" to escape \"double\" quotes"
顺便说一下,它是字符串:
'"occasionally I \\"need\\" to escape \\"double\\" quotes"'
您的“实际查询”也是如此:
query = '"\\"datadog.agent.up\\".over(\\"role:dns\\").by(\\"host\\").last(1).count_by_status()"'
给
print json.dumps(query)
# "\"datadog.agent.up\".over(\"role:dns\").by(\"host\").last(1).count_by_status()"
with open('myfile.txt', 'w') as f:
f.write(json.dumps(query))
# file contents:
# "\"datadog.agent.up\".over(\"role:dns\").by(\"host\").last(1).count_by_status()"
双\\\\
:
瞧,这就是为什么您需要明确说明您实际要做什么。
\\
翻倍的诀窍是放入repr()
例如:
print repr(json.dumps(query))[1:-1] # to remove the ' from the beginning and end
# "\\"datadog.agent.up\\".over(\\"role:dns\\").by(\\"host\\").last(1).count_by_status()"
with open('myfile.txt', 'w') as f:
f.write(repr(json.dumps(actual_query))[1:-1])
# file:
# "\\"datadog.agent.up\\".over(\\"role:dns\\").by(\\"host\\").last(1).count_by_status()"
您也可以在其上执行.replace(r'\\', r'\\\\')
当我运行您的程序时,得到的json看起来有些不同。 您在输出的第二行附近有单引号。 我不明白
无论如何。 虽然单引号解决了转义问题,但它不是有效的Json。 有效的Json需要双引号。 单引号只是Python中的字符串定界符。
用print(json.dumps(file))
替换代码中的最后一行
并返回正确的json。 { "query": "occasionally I \\"need\\" to escape \\"double\\" quotes", "version": 1 }
问候,
梅勒
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.