Convert stringified list of dictionaries back to a list of dictionaries

前端 未结 3 355
时光取名叫无心
时光取名叫无心 2021-01-19 04:17

I know that to convert a dictionary to/from a string, I use json.loads and json.dumps. However, those methods fail when given a string representing

3条回答
  •  抹茶落季
    2021-01-19 05:00

    Converting that to a string with str() gives us...

    There's your problem right there. You shouldn't be using str to serialize data. There's no guarantee that the resulting string will be something that can be recovered back into the original object.

    Instead of using str(), use json.dumps. I know you said you tried it and it didn't work, but it's quite robust when used on built-in objects, so I suspect you may have just accidentally made a typo. The example dict you give serializes perfectly:

    >>> sample_entry = [
    ...     {"type": "test", "topic": "obama", "interval": "daily"},
    ...     {"type": "test", "topic": "biden", "interval": "immediate"},
    ... ]
    >>>
    >>> s = json.dumps(sample_entry)
    >>> print(s)
    [{"interval": "daily", "topic": "obama", "type": "test"}, {"interval": "immediate", "topic": "biden", "type": "test"}]
    >>>
    >>> d = json.loads(s)
    >>> d
    [{'interval': 'daily', 'topic': 'obama', 'type': 'test'}, {'interval': 'immediate', 'topic': 'biden', 'type': 'test'}]
    

提交回复
热议问题