Vlad Cenan
Vlad Cenan

Reputation: 172

Remove quotes from a json in a key value iteration

I want to add some users based on a dictionary with pymongo, but pymongo fails to validate role and db because I'm getting the value with quotes:

USERS = {
      "topology": "{'role': 'readWrite', 'db': 'ui'},{'role': 'readWrite', 'db': 'linkage'},{'role': 'readWrite', 'db': 'metrics'},{'role': 'readWrite', 'db': 'migrations'},{'role': 'readWrite', 'db': 'state'},{'role': 'readWrite', 'db': 'storm'}",
      "uiWriter": "{'role': 'readWrite', 'db': 'ui'}",
      "reports": "{'role': 'readWrite', 'db': 'ui'}",
      "dr": "{'role': 'clusterAdmin', 'db': 'admin'}",
      "eventapi": "{'role': 'readWrite', 'db': 'dedup'},{'role': 'readWrite', 'db': 'lookup'}"
    }
for k,v in USERS.items():
    client = MongoClient(mongos,
                        username=mongo_admin_user,
                        password=mongo_admin_pass,
                        authSource='admin')
    client.admin.add_user(k, mongo_key[k], roles=[v])
    print({v}) 

If I print the value with brackets print({v}) the quotes are visible. I tried with replace but doesn't work. I also tried changing the quotes double with single without luck. If I put the value roles=[{'role': 'readWrite', 'db': 'ui'}] overwritten, it works and validates. Error:

"errorMessage": "No role named {'role': 'readWrite', 'db':

Upvotes: 0

Views: 97

Answers (5)

abhilb
abhilb

Reputation: 5757

You need a array of dicts as value for roles. So may be try this.

>>> from ast import literal_eval
>>> roles_value = []
>>> for k,v in USERS.items():
...     roles_value = list(literal_eval(v))

P.S. add_user function is deprecated..

Upvotes: 1

Kirikkayis
Kirikkayis

Reputation: 83

You can use regex. (with import json) Example: r"[a-zA-Z]+

Upvotes: 0

Dinesh Sakthivel
Dinesh Sakthivel

Reputation: 574

Try this,

for k,v in json.loads(json.dumps(USERS)).items():
    print k, v

Upvotes: 1

dangee1705
dangee1705

Reputation: 3520

You need to change the values into actual objects. You can do this with

import json
USERS = {k: json.loads(v) for k, v in USERS}

Upvotes: 1

Fnguyen
Fnguyen

Reputation: 1177

Your string does not have "" or '' around it, rather it is of type string which is obviously expressed with quotes. So regex, replace, etc. won't help evaluate as an expression instead of a string.

I am pretty sure eval() or ast.literal_eval() should work for your case, with the second one being preferred.

Note that many people dissuade the use of eval().

Upvotes: 0

Related Questions