Zaks
Zaks

Reputation: 700

String to list python conversion

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

Upvotes: 2

Views: 103

Answers (2)

thebjorn
thebjorn

Reputation: 27360

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

Upvotes: 2

gph
gph

Reputation: 1359

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.

Upvotes: 1

Related Questions