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
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'}]