I know there are a lot of other posts about parsing comma-separated values, but I couldn't find one that splits key-value pairs and handles quoted commas.
I have strings like this:
age=12,name=bob,hobbies="games,reading",phrase="I'm cool!"
And I want to get this:
{
'age': '12',
'name': 'bob',
'hobbies': 'games,reading',
'phrase': "I'm cool!",
}
I tried using shlex
like this:
lexer = shlex.shlex('''age=12,name=bob,hobbies="games,reading",phrase="I'm cool!"''')
lexer.whitespace_split = True
lexer.whitespace = ','
props = dict(pair.split('=', 1) for pair in lexer)
The trouble is that shlex
will split the hobbies
entry into two tokens, i.e. hobbies="games
and reading"
. Is there a way to make it take the double quotes into account? Or is there another module I can use?
EDIT: Fixed typo for whitespace_split
EDIT 2: I'm not tied to using shlex
. Regex is fine too, but I didn't know how to handle the matching quotes.