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 2
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': '='}]]
answered Dec 9, 2020 at 7:03
thebjorn
27.6k12 gold badges107 silver badges152 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Amit Amola
I believe OP should accept this as the answer. I infact learned something new here today. That's a nice thing to share @thebjorn
Zaks
@thebjron if the input is changed to ['xor',[{'asset':'pc','operator':'=','basis':true}]] I cant run eval on it . anyways to overcome that
thebjorn
It's early Sunday morning here, but I don't see what the change is? If you mean that the ordering of keys in the dict is different, then you just need to upgrade to a Python version that preserves dict-key order (don't remember when that was changed off the top of my head...)
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.
4 Comments
gph
That seems like something that can pretty easily be corrected with replace()
wjandrea
yep,
rule.replace("'", '"')juanpa.arrivillaga
@gph no actually, in general, it can't. But it may suffice for the OP's purposes
gph
which is why I said the solution will depend on the details.
lang-py
truesupposed to be?