I saved some username, password, host, port, and other things related to database connection as a string in the database. I want to use MySQLdb to check the connection information of these databases, you need to pass the username, password, host, port, and other information in the database information to MySQLdb as parameters. connect (). In this case, '{"host": "192.168.11.22 & Prime;," port ": 3306," user ":" abc "," passwd ":" 123 & Prime ;, "db": "mydb", "connect_timeout": 10} '"and other strings are converted to dict.
In python, convert string to a dict. I know the following three methods:
1. ast. literal_eval () is commonly used by me. It depends on python2.6 or above. According to the introduction, it is safer than direct eval.
2. eval () is a good method on the premise that the string content is controllable and secure.
3. json. loads () the loads method provided by json is good, but the string in key/value is converted to unicode.
View instance code: https://github.com/smilejay/python/blob/master/py2014/string2dict.py
The code is as follows: |
Copy code |
''' Created on Oct 14,201 4 @ Author: Jay <smile665@gmail.com> ''' Import MySQLdb Import ast Import json Def my_run (): Try: S = '{"host": "192.168.11.22", "port": 3306, "user": "abc ", "Passwd": "123", "db": "mydb", "connect_timeout": 10 }' D = ast. literal_eval (s) Print type (d) Print d D1 = eval (s) Print type (d1) Print d1 D2 = json. loads (s) Print type (d2) Print d2 MySQLdb. Connect (host = d ['host'], port = d ['port'], user = d ['user'], Passwd = d ['passwd'], db = d ['DB'], Connect_timeout = d ['connect _ timeout']) Print 'right' Except t Exception, e: Print 'wrong % s' % e If _ name _ = '_ main __': My_run () |