Convert a String representation of a Dictionary to a dictionary?

前端 未结 9 978
醉酒成梦
醉酒成梦 2020-11-21 05:22

How can I convert the str representation of a dict, such as the following string, into a dict?

s = \"{\'muffin\' : \'l         


        
9条回答
  •  长发绾君心
    2020-11-21 05:35

    https://docs.python.org/3.8/library/json.html

    JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...

    import json
    s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
    json_acceptable_string = s.replace("'", "\"")
    d = json.loads(json_acceptable_string)
    # d = {u'muffin': u'lolz', u'foo': u'kitty'}
    

    NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.

    More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

提交回复
热议问题