在 Groovy 中使用 JsonOutput 向 JSON 文件元素添加了不必要的引号

Unnecessary quotes added to JSON file elements using JsonOutput in Groovy

我的 Groovy 脚本正在创建一个 JSON 文件,如下所示:

JSON output

进入 hsps 数组的元素数量是可变的。基本上,我的输出是正确的,但脚本向元素添加了不必要的引号。相关代码如下所示:

    foundPlasmids.each {
    def tempHSPs = []
    it.hsps.each{
        def hsps = JsonOutput.toJson(
            [bit_score: it.bit_score, 
            evalue: it.evalue, 
            score: it.score, 
            query_from: it.query_from,
            query_to: it.query_to,
            hit_from: it.hit_from,
            hit_to: it.hit_to,
            align_len: it.align_len,
            gaps: it.gaps]
        )
        tempHSPs << JsonOutput.prettyPrint(hsps)
    }

    def output = JsonOutput.toJson(
        [contig: it.contig, title: it.title, accNumber: it.accession, length: it.length, noHSPs: it.noHsps, hsps: tempHSPs]
    )

    prettyOutput << JsonOutput.prettyPrint(output)
}

foundPlasmids 是包含所有信息的散列,包括 hsps 数组。我 prettyPrint 将所有 hsps 数组放入 tempHSPs 并将 tempHSPs 传递给 output。我不明白为什么要添加额外的引号,也想不出将 hsps 数组传递到 output 的不同方法。 感谢您的帮助。

您放入 tempHSPs 数组的对象是 JSON 的字符串表示形式,它们由 prettyPrint 函数生成。 JsonOutput return 字符串中的所有 toJson 函数,prettyPrint 接受一个字符串,对其进行格式化,然后 returns 一个字符串。

没有放入tempHSPs 的是实际的JSON 对象或数组。您正在输入一个字符串,因此最终输出在每个顶级元素中包含一个包含单个字符串值的数组 "hsps"。

这有两个问题。

一个是调用 def output = JsonOutput.toJson 时字符串没有被正确转义,我只能假设这是 JsonOutput class 中的错误?这似乎不太可能,但我没有更好的解释。它应该看起来更像...

[
    {
        "nohsps": 1,
        "hsps": [
            "{\r\n    \"bit_score\": 841.346,\r\n    \"evalue\": 0,\r\n    (and so on)\r\n}"
        ]
    },
    {
        "nohsps": 6,
        "hsps": [
            "{\r\n    \"bit_score\": 767.48,\r\n    \"evalue\": 0,\r\n    (and so on)\r\n}"
        ]
    }
]

第二个问题是,听起来您不想要字符串而是想要 JSON 对象,所以停止将您的 Groovy 对象转换为字符串...

def tempHSPs = []
it.hsps.each{
    def hsps =
        [bit_score: it.bit_score, 
        evalue: it.evalue, 
        score: it.score, 
        query_from: it.query_from,
        query_to: it.query_to,
        hit_from: it.hit_from,
        hit_to: it.hit_to,
        align_len: it.align_len,
        gaps: it.gaps]
    )
    tempHSPs << hsps
}

或者,如果要简化的话,把tempHSPs那些东西全部删掉,让JsonObject自动序列化,看看自动出来的东西:

def output = JsonOutput.toJson(
        [contig: it.contig, title: it.title, accNumber: it.accession, length: it.length, noHSPs: it.noHsps, hsps: foundPlasmids*.hsps ]
    )

(我还没有验证这个语法;我只是在消耗内存。)

如果它在 hsps 对象上阻塞或者您不喜欢生成的输出(例如,如果您想删除或重命名某些属性),请像现在一样继续制作地图。