【问题标题】:JSONBuilder in Groovy adds wrong quotation marksGroovy 中的 JSONBuilder 添加了错误的引号
【发布时间】:2022-01-22 20:32:00
【问题描述】:

我正在尝试读取 json 文件,编辑其中的某些部分,然后将其解析回 json 文件。目标是改变汇合页面的价值。我在 Jenkins 管道中使用 groovy 代码。这里是:

def changeValue(){
def json_map = readJSON file: '/tmp/updater.json'

def body_content = '{"storage":{"value":'
body_content += '"<h1>test</h1>"'
body_content += ',"representation":"storage"}}'

json_map.body = body_content

json_as_string = new JsonBuilder(json_map).toPrettyString().replaceAll("\\\\", "") // It also adds unneccesary escapes

print json_as_string
}

这是updater.json的内容:

{
    "id":"redacted",
    "type":"page",
    "title":"redacted",
    "space":{"key":"redacted"},
    "body":{"storage":{"value":"<h1>wrong</h1>","representation":"storage"}},
    "version":{
        "number":6
        }
}

这就是我得到的:

{
"id": "redacted",
"type": "page",
"title": "redacted",
"space": {
    "key": "redacted"
},
"body": "{"storage":{"value":"<h1>test</h1>","representation":"storage"}}",
"version": {
    "number": 6
}
}

如您所见,它在正文块周围添加了引号。我怎样才能摆脱它们?

【问题讨论】:

    标签: json jenkins groovy


    【解决方案1】:

    结果如预期,您将body 更新为新的String。

    如果您只想更新 value,请根据 this answer 使用它

    导入 groovy.json.JsonBuilder 导入 groovy.json.JsonSlurper

    def jsn = """
    {
        "id":"redacted",
        "type":"page",
        "title":"redacted",
        "space":{"key":"redacted"},
        "body":{"storage":{"value":"<h1>wrong</h1>","representation":"storage"}},
        "version":{
            "number":6
            }
    }"""
    
    def slp= new JsonSlurper().parseText(jsn)
    bld.content.body.storage.value = '<h1>test</h1>'
    println(bld.toPrettyString())  
    

    结果

    {
        "id": "redacted",
        "type": "page",
        "title": "redacted",
        "space": {
            "key": "redacted"
        },
        "body": {
            "storage": {
                "value": "<h1>test</h1>",
                "representation": "storage"
            }
        },
        "version": {
            "number": 6
        }
    }
    

    【讨论】:

    • 非常感谢。我仍在试图弄清楚如何正确处理 JSON 等。你帮了我很多!
    猜你喜欢
    • 2018-07-26
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多