I have the following string in a report file:
"Bunch(conditions=['s1', 's2', 's3', 's4', 's5', 's6'], durations=[[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]], onsets=[[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])"
I would like to turn it into a Bunch()
object or a dict
, so that I can access the information inside (via either my_var.conditions
or my_var["conditions"]
).
This works very well with eval()
:
eval("Bunch(conditions=['s1', 's2', 's3', 's4', 's5', 's6'], durations=[[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]], onsets=[[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])")
however I would like to avoid using that.
I have tried to write a couple of string substitutions so that I convert it to a dict syntax and then parse it with json.loads()
but that looks very very hackish, and will break as soon as I encounter any new fields in future strings; e.g.:
"{"+"Bunch(conditions=['s1', 's2', 's3', 's4', 's5', 's6'], durations=[[30.0], [30.0], [30.0], [30.0], [30.0], [30.0]], onsets=[[172.77], [322.77], [472.77], [622.77], [772.77], [922.77]])"[1:-1]+"}".replace("conditions=","'conditions':")
You get the idea.
Do you know if there is any better way to parse this?