简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM