Search code examples
pythonjsonpymongoquotes

Opposite single/double quotes using pymongo command


I am trying to take user input, create a URI, and add it with a collection in Pymongo, but whenever I try to do this, the format gets messed up and I cant figure out how to fix it. When running the line:

print(db.command("create", "storage", someStorage={ "URI": {FS_URI}}))

where "Storage" is the collection, I want the object to be {"fs" : "something://a:b"} or {'fs' : 'something://a:b'}

 FS_URI = ('\"fs\" : \"'+URI+'\"')

gives the error: Cannot encode object: {'"fs" : "something://a:b"'}

FS_URI = ("fs\" : \"%s" % URI)

gives the error" Cannot encode object: {'fs" : "something://a:b'}

FS_URI = ("fs\' : \'%s" % URI)

gives the error" Cannot encode object: {"fs' : 'something://a:b"}

The quotes are always unmatching, or have extra quotes around them. I have tried the command with the actual URI in the quote format I want, and it runs perfectly.


Solution

  • I found that using a dict solved this problem, by changing

    FS_URI = ("fs\" : \"%s" % URI)
    

    to a JSON object rather than a string:

    FS_URI = {"fs": "{}".format(URI)}
    

    solved this problem