Julian
Julian

Reputation: 109

JSONBuilder in Groovy adds wrong quotation marks

I'm trying to read a json file, edit some parts of it and then parse it back to a json file. The goal is to change the value of a confluence page. I'm using the groovy code in a Jenkins pipeline. Here it is:

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
}

This is the contents of the updater.json:

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

That is what I get:

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

As you can see, it added quotation marks around the block of the body. How can I get rid of them?

Upvotes: 0

Views: 184

Answers (1)

Marmite Bomber
Marmite Bomber

Reputation: 21075

The result is as expected, you update the body with a new String.

If you want to update only the value use this based on this answer

import groovy.json.JsonBuilder import 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())  

result

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

Upvotes: 1

Related Questions