[英]String to list python conversion
My input string looks like below我的输入字符串如下所示
rule = "['xor',[{'asset':'pc','operator':'=','basis':true}]]"
Expected output预期 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'这也是我无法执行
ast.literal_eval(rule)
的遗留代码,因为基础具有非字符串值true
,这将引发错误“格式错误的字符串”
Any suggestions to do the same?有什么建议做同样的事情吗?
I tried with rule.strip('][').split(', ')
, but the output is not the expected format:我尝试使用
rule.strip('][').split(', ')
,但 output 不是预期的格式:
["'and',[{'fact':'waived','operator':'=','basis':true}"]
If you're OK with using eval, then you can define true
in the environment to eval:如果您可以使用 eval,那么您可以在 eval 环境中定义
true
:
>>> 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.我认为如果您不在这些字符串中使用元组,您可以将其解析为 json。
import json
my_data = json.loads(my_string)
This will depend on the details of what you parsing though so buyer beware.这将取决于您解析的内容的详细信息,但请注意买家。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.