Retrieving escaped characters using PyMongo

I’m using pymongo to access MongoDB from python.

I have a collection with a document that include escaped quotes:

{
    "_id" : ObjectId("5e57d89d5a7f537828c12a53"),
    "field" : "my \"string\" with escaped chars"
}

However ,when I retrieve the document like this:

doc = collection.find_one({})
print(doc)

I get this:

{'_id': ObjectId('5e57d89d5a7f537828c12a53'), 'field': 'my "string" with escaped chars'}

which is not what I want as the escaped quotes have disappeared.

What should I do to retrieve the document as is in the database, that is, with the escaped quotes?

Thanks

Any reason why you want the backslash? In principle you use the backslash in your code because you want the quotes. I am not sure in python but in some other languages you put 3 backslashes. The first one escapes the second one and the third escape the quotes.

When you use it, why don’t you define your string as raw using r’text’? I should keep escape characters.

Thanks @steevej and @coderkid.

I do need the backslashes. Actually, the documents I want to retrieve are much more complicated than
the simple example I gave, and they are in a database that I cannot modify.

The documents are correctly retrieved by a Java application, but for some reason pymongo “unescapes” the backslashes.

Ok, so I’ve found what the problem was. It’s the “print” bit, that is not displaying the backslashes. My code was actually doing a return str(doc) as it was a REST API server. The str was then removing the backslashes.

I’ve changed that for return json.dumps(doc) and it keeps them.

So problem solved!

2 Likes