This is exactly what you should be expecting, and I'm not sure why it isn't what you want. Remember that print
commands return the representation of a variable, eg print('\"')
gives "
.
using your example, you can see how you would get the escape characters back when outputting your results:
import json
a = r"""{
"version": 1,
"query": "occasionally I \"need\" to escape \"double\" quotes"
}"""
j = json.loads(a)
print j
print json.dumps(j)
which gives me:
{u'query': u'occasionally I "need" to escape "double" quotes', u'version': 1}
{"query": "occasionally I \"need\" to escape \"double\" quotes", "version": 1}
(if you'll excuse the python2)
In repsonse to your edit:
'{}'.format(file['query']) == file['query']
returns True
- you're formatting a string object as a string. As I have suggested, using
json.dumps(file['query'])
returns
"occasionally I \"need\" to escape \"double\" quotes"
which by the way is the string:
'"occasionally I \\"need\\" to escape \\"double\\" quotes"'
this is the case also for your 'actual query':
query = '"\\"datadog.agent.up\\".over(\\"role:dns\\").by(\\"host\\").last(1).count_by_status()"'
gives
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()"
double \\
:
see, this is why you need to be explicit about what you're actually trying to do.
a trick for doubling \
is to put in a repr()
eg:
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()"
you could also do a .replace(r'\', r'\\')
on it