您可以从 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'}]}
希望对你有帮助。