python json dumps

前端 未结 4 1006
予麋鹿
予麋鹿 2020-12-15 17:46

i have the following string, need to turn it into a list without u\'\':

my_str = \"[{u\'name\': u\'squats\', u\'wrs\': [[u\'99\', 8]], u\'id\': 2}]\"
         


        
相关标签:
4条回答
  • 2020-12-15 18:07
    >>> "[{\"id\": 2, \"name\": \"squats\", \"wrs\": [[\"55\", 9]]}]".replace('\\"',"\"")
    '[{"id": 2, "name": "squats", "wrs": [["55", 9]]}]'
    

    note that you could just do this on the original string

    >>> "[{u'name': u'squats', u'wrs': [[u'99', 8]], u'id': 2}]".replace("u\'","\'")
    "[{'name': 'squats', 'wrs': [['99', 8]], 'id': 2}]"
    
    0 讨论(0)
  • 2020-12-15 18:09

    This works but doesn't seem too elegant

    import json
    json.dumps(json.JSONDecoder().decode(str_w_quotes))
    
    0 讨论(0)
  • 2020-12-15 18:18

    You don't dump your string as JSON, rather you load your string as JSON.

    import json
    json.loads(str_w_quotes)
    

    Your string is already in JSON format. You do not want to dump it as JSON again.

    0 讨论(0)
  • 2020-12-15 18:20

    json.dumps thinks that the " is part of a the string, not part of the json formatting.

    import json
    json.dumps(json.load(str_w_quotes))
    

    should give you:

     [{"id": 2, "name": "squats", "wrs": [["55", 9]]}]
    
    0 讨论(0)
提交回复
热议问题