Scenario 1: perfectly formatted value
import shlexvalue_str = 'name="Desmond Lua",age=40,gender=M,friends="James, Ramesh, K\'to, 小爱"'# posix=True - remove quotes of string in final values = shlex.shlex(value_str, posix=True)s.whitespace_split = Trues.whitespace = ', \n'data = dict(pair.split('=', 1) for pair in s)
{
'name': 'Desmond Lua',
'age': '40',
'gender': 'M',
'friends': "James, Ramesh, K'to, 小爱"
}
Scenario 2: whitespace and comma as separator
import shlexvalue_str = 'name="Desmond Lua",\tage=40, gender=M,\nfriends="James, Ramesh, K\'to, 小爱"'s = shlex.shlex(value_str, posix=True)s.whitespace_split = Trues.whitespace = ', \n\t'data = dict(pair.split('=', 1) for pair in s)
NOTE: This solution doesn't work if the is space in key-value pair (e.g. name = "Desmond Lua"
)
Scenario 3: spaces in key value pair
import shleximport revalue_str = 'name = "Desmond Lua" ,\tage=40, gender=M,\nfriends="James, Ramesh, K\'to, 小爱"'s = shlex.shlex(value_str, posix=True)s.whitespace_split = Trues.whitespace = ','p = re.compile(r'\s*=\s*')data = dict(p.split(pair.strip(), maxsplit=1) for pair in s)
NOTE: This assume the actual key/value doesn't have whitespace on left and right.
References: