String to list python conversion

Viewed 91

My input string looks like below

rule = "['xor',[{'asset':'pc','operator':'=','basis':true}]]"

Expected output

 Output = ['xor',[{'asset':'pc','operator':'=','basis':true}]]

Also this is legacy code where I cannot do ast.literal_eval(rule) since basis has non-string value true which will throw error 'malformed string'

Any suggestions to do the same?

I tried with rule.strip('][').split(', '), but the output is not the expected format:

["'and',[{'fact':'waived','operator':'=','basis':true}"]
2 Answers

If you're OK with using eval, then you can define true in the environment to eval:

>>> rule = "['xor',[{'asset':'pc','operator':'=','basis':true}]]"
>>> print(eval(rule, {'true': True}))
['xor', [{'basis': True, 'asset': 'pc', 'operator': '='}]]

I think if you are not using tuples in those strings you could parse it as json.

import json
my_data = json.loads(my_string)

This will depend on the details of what you parsing though so buyer beware.

Related