2

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}"]
5
  • What is true supposed to be? Commented Dec 9, 2020 at 4:35
  • 2
    Is this thing supposed to be some kind of wrongly-quoted JSON? Commented Dec 9, 2020 at 4:35
  • The true should ideally be a json but not be in legacy code ,have to handle that condition in the code Commented Dec 9, 2020 at 4:43
  • true should ideally have been passed as 'true' from UI to backend - which is not ought to be in legacy code Commented Dec 9, 2020 at 6:49
  • true is defined in JavaScript while it is True in Python hence the mismatch Commented Dec 9, 2020 at 20:23

2 Answers 2

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': '='}]]
Sign up to request clarification or add additional context in comments.

3 Comments

I believe OP should accept this as the answer. I infact learned something new here today. That's a nice thing to share @thebjorn
@thebjron if the input is changed to ['xor',[{'asset':'pc','operator':'=','basis':true}]] I cant run eval on it . anyways to overcome that
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...)
1

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

That seems like something that can pretty easily be corrected with replace()
yep, rule.replace("'", '"')
@gph no actually, in general, it can't. But it may suffice for the OP's purposes
which is why I said the solution will depend on the details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.