Python3:
>>> b'\\u201c'.decode('unicode_escape')
'“'
or
>>> '\\u201c'.encode().decode('unicode_escape')
'“'
Answer from max5555 on Stack OverflowPython3:
>>> b'\\u201c'.decode('unicode_escape')
'“'
or
>>> '\\u201c'.encode().decode('unicode_escape')
'“'
You can try codecs.escape_decode, this should decode the escape sequences.
python - json.dumps() : how to escape double quotes with a single backslash - Stack Overflow
python replace single backslash with double backslash
python - Converting backslash single quote \' to backslash double quote \" for JSON - Stack Overflow
Manage double backslashes added automatically by JSON in python - Stack Overflow
why not use string.replace()?
>>> s = 'some \\\\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles
Or with "raw" strings:
>>> s = r'some \\ doubles'
>>> print s
some \\ doubles
>>> print s.replace('\\\\', '\\')
some \ doubles
Since the escape character is complicated, you still need to escape it so it does not escape the '
Just use .replace() twice!
I had the following path: C:\\Users\\XXXXX\\Desktop\\PMI APP GIT\\pmi-app\\niton x5 test data
To convert \ to single backslashes, i just did the following:
path_to_file = path_to_file.replace('\\','*')
path_to_file = path_to_file.replace('**', '\\')
first operation creates ** for every \ and second operation escapes the first slash, replacing ** with a single \.
Result:
C:**Users**z0044wmy**Desktop**PMI APP GIT**pmi-app**GENERATED_REPORTS
C:\Users\z0044wmy\Desktop\PMI APP GIT\pmi-app\GENERATED_REPORTS
Not sure if this is exactly what you want, but it might be:
import json
print(json.dumps("abc").replace(r'\"', '"').replace('"', r'\"'))
Result:
\"abc\"
It sounds like what you're asking for is double-encoded JSON.
print(json.dumps(json.dumps("abc")))
...results in:
"\"abc\""
By contrast, single-encoding (without the REPL's implicit repr()) looks like:
print(json.dumps("abc"))
...and emits the correctly-encoded JSON document:
"abc"
Note that this is correct JSON exactly as it is; no backslashes are needed.
Instead of focusing on the backslashes to try to "hack" a json string / dict str into a JSON, a better solution is to take it one step at a time and start by converting my dict string into a dictionary.
import ast
txt = ast.literal_eval(txt) # convert my string to a dictionary
txt = json.loads(json.dumps(txt)) # convert my dict to JSON
i mean,
my_string = "\"\'"
print(my_string.replace("\'", "\""))
works perfectly fine
EDIT: i didn't mean use this directly, it was a proof of concept. In mine the replacement was reversed. I have updated this snippet such that it could directly be put into your code. Try it again
You are seeing an escaped forward slash. The JSON standard allows any character to be escaped, and the forward slash can be escaped by preceding it with a backward slash. See the Strings section of RFC 7159.
So \/ is an just an escaped representation for the value /:
>>> import json
>>> print json.loads(r'{"date": "\/Date(1411084800000)\/"}')
{u'date': u'/Date(1411084800000)/'}
Note how the \/ is decoded to / in the output. This escaping is entirely optional.
Your browser does the same thing; when any compliant JSON value which includes strings containing \/ sequences is being parsed, the resulting string values containg just / forward slashes. When the Kendo JSONP response (which does use \/ in strings) is received, the browser produces the exact same result as a JSONP response with the forward slashes left un-escaped.
Just provide the value in Python with the forward slashes. json.dumps() will not escape the forward slash (it doesn't have to escape it), and your browser and any other JSON compliant parser will produce the exact same value:
>>> print json.dumps({'date': '/Date(1411084800000)/'})
{"date": "/Date(1411084800000)/"}
While Martijn is absolutely correct, he does include a caveat about the far end being compliant. If it isn't, like JustGiving, then you might find the following a useful starting point:
class DateJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime.date):
javascript_date = int(o.strftime("%s"))*1000
return r'\/Date({0}+0000)\/'.format(javascript_date)
return JSONEncoder.default(self, o)
def encode(self, o):
encoded = super(DateJSONEncoder, self).encode(o)
encoded = encoded.replace(r"\\/", r"\/").replace(r")\\/", r")\/")
return encoded
I'm writing my first python code so i'm not familiar with any libraries etc.
I have this json string
"{\"systemUri\":\"https://myserver:443/bc-testrest/ODataV4\",\"dateTime\":\"06/20/24 11:53 AM\",\"applicationOK\":true,\"databaseOK\":true}" and my goal is to convert it to a regular json string like this
{"systemUri":"https://myserver:443/bc-testrest/ODataV4","dateTime":"06/20/24 11:53 AM","applicationOK":true,"databaseOK":true} so i can load it into a python dict with json.loads. How can i do that?
\\ is not double backslash but one escaped. Look:
print b'Z\xa6\x97\x86j2\x08q\\r\xca\xe6m'
# Z���jq\r��m
And \r (from your desired output) is not 2 chars but one:
print b'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'
# ��m�jq
(When printing it to terminal, carriage return \r prevents us from seen the first letter Z)
If you really want to replace '\\r' with '\r', you can do:
print repr(word.replace('\\r', '\r'))
# 'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'
print word.replace('\\r', '\r')
# ��m�jq
Or, if you want to replace all the escape sequences. Python2 version:
print repr(b'1\\t2\\n3'.decode('string_escape'))
# '1\t2\n3'
print b'1\\t2\\n3'.decode('string_escape')
# 1 2
# 3
Python3 version:
print(repr(b'1\\t2\\n3'.decode('unicode_escape')))
# '1\t2\n3'
print(b'1\\t2\\n3'.decode('unicode_escape'))
# 1 2
# 3
your \r is a carriage return character. So \\r is \ plus carriage return. You won't find \\ in your string.
What "works" is to replace backslash+CR by just CR:
word = b'Z\xa6\x97\x86j2\x08q\\r\xca\xe6m'
print(word.replace(b"\\r",b"\r"))
result:
b'Z\xa6\x97\x86j2\x08q\r\xca\xe6m'
but I'm not sure that's what you meant from the start (that is: inserting a carriage return char in your bytes string)