How to split comma-separated key-value pairs with quoted commas

后端 未结 5 1503
终归单人心
终归单人心 2021-01-02 13:03

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 st

5条回答
  •  一个人的身影
    2021-01-02 13:52

    Ok, I actually figured out a pretty nifty way, which is to split on both comma and equal sign, then take 2 tokens at a time.

    input_str = '''age=12,name=bob,hobbies="games,reading",phrase="I'm cool!"'''
    
    lexer = shlex.shlex(input_str)
    lexer.whitespace_split = True
    lexer.whitespace = ',='
    
    ret = {}
    try:
      while True:
        key = next(lexer)
        value = next(lexer)
    
        # Remove surrounding quotes
        if len(value) >= 2 and (value[0] == value[-1] == '"' or
                                value[0] == value[-1] == '\''):
          value = value[1:-1]
    
        ret[key] = value
    
    except StopIteration:
      # Somehow do error checking to see if you ended up with an extra token.
      pass
    
    print ret
    

    Then you get:

    {
      'age': '12',
      'name': 'bob',
      'hobbies': 'games,reading',
      'phrase': "I'm cool!",
    }
    

    However, this doesn't check that you don't have weird stuff like: age,12=name,bob, but I'm ok with that in my use case.

    EDIT: Handle both double-quotes and single-quotes.

提交回复
热议问题