pythonjsonload转义_Python:防⽌json.load⽂件(⽂件)从
剥离转义字符
这正是你应该期待的,我不知道为什么它不是你想要的。记住,print命令返回⼀个变量的表⽰,例如print('\"')给出{}。在
通过您的⽰例,您可以看到在输出结果时如何将转义字符取回:import json
a = r"""{
"version": 1,
ajax希腊神话"query": "occasionally I \"need\" to escape \"double\" quotes"
python解析json文件}"""
c语言设计谭浩强电子书j = json.loads(a)
print j
print json.dumps(j)
这给了我:
^{pr2}$
(请原谅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('', 'w') as f:
f.write(json.dumps(query))
# file contents:
css导航条美化立体
# "\"datadog.agent.up\".over(\"role:dns\").by(\"host\").last(1).count_by_status()"
双\\:
linux系统界面设置语言看,这就是为什么你需要明确你到底想做什么。在
加倍\的⼀个技巧是放⼊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('', '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'\\')通达oa源码