【问题标题】:Parse flat file python dict into groovy将平面文件 python dict 解析为 groovy
【发布时间】:2017-09-08 08:03:02
【问题描述】:

我是 Groovy 的新手,我有一个 Python 格式的平面文件。它不包含任何代码,它只是生成一个 Python 字典。

所以 Python 看起来类似于:

bob = {}
bob["names"] = []
bob["names"][0] = {}
bob["names"][0]["nick"] = "wobbly bob"

它只是定义了字典。

我目前正在用 groovy 解析代码,使用大量拆分、替换和条件将其转化为某种东西,它可以工作,但我不禁想到必须有一种更优雅的方式。

那么有谁知道我可以用来解析这类信息的好 groovy 库吗?

【问题讨论】:

标签: groovy


【解决方案1】:

您可以从 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'}]}

希望对你有帮助。

【讨论】:

  • 你也可以import groovy.json.JsonParserType,然后就这样做:new JsonSlurper().setType(JsonParserType.LAX).parseText(result)(不需要字符替换)
  • 谢谢,这真的很有帮助。对不起,这个例子不起作用..从记忆中输入
猜你喜欢
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多