我对Groovy来说是新手,我有一个python中的平面文件。它不包含任何代码,它只是生成python词典。
所以Python看起来与以下内容相似:
bob = {}
bob["names"] = []
bob["names"][0] = {}
bob["names"][0]["nick"] = "wobbly bob"
只是定义了dict。
我目前正在用大量的分裂,替换和有条件地将其转化为某种东西,它有效,但我不禁认为必须有一种更优雅的方式。
那么,有人知道我可以用来解析这种信息的好的凹槽库吗?
您可以从Groovy脚本内部运行Python脚本。以以下示例来看:
test.py
bob = {"names":[{"nick": "wobbly bob"}]}
print(bob)
重要:您的脚本必须产生任何输出,以便Groovy可以解析它。这就是为什么我将
print(bob)
放在脚本的末尾。
test.groovy
import groovy.json.JsonSlurper
import groovy.json.JsonParserType
def cmd = ["python", "test.py"]
def result = cmd.execute()
def json = new JsonSlurper().setType(JsonParserType.LAX).parseText(result.text)
println json
为了简单起见,两个文件都必须放在同一文件夹中。
运行groovy test.groovy
产生以下输出:
[names:[[nick:wobbly bob]]]
请记住,Python脚本会生成以下输出:
{'names': [{'nick': 'wobbly bob'}]}
这就是为什么我们致电.setType(JsonParserType.LAX)
(信用tim_yates提出了这种方法而不是用双引号替换所有单个引号)也接受单句话,否则Groovy会抱怨:
Caught: groovy.json.JsonException: expecting '}' or ',' but got current char ''' with an int value of 39
The current character read is ''' with an int value of 39
expecting '}' or ',' but got current char ''' with an int value of 39
line number 1
index number 1
{'names': [{'nick': 'wobbly bob'}]}
.^
groovy.json.JsonException: expecting '}' or ',' but got current char ''' with an int value of 39
The current character read is ''' with an int value of 39
expecting '}' or ',' but got current char ''' with an int value of 39
line number 1
index number 1
{'names': [{'nick': 'wobbly bob'}]}
我希望它有帮助。