Jenkinsfile pipeline construct JSON object and write to file

情到浓时终转凉″ 提交于 2019-12-14 01:23:38

问题


I would like to construct a JSON object and write the content to file.

Originally I was inspired by this and tried:

def data = [
        a:"test: ${myVar}"
    ]
    writeJSON(file: 'message1.json', json: data)

But this failed with:

Could not instantiate {file=message1.json, json={a=test}} for WriteJSONStep(file: String, json: JSON{}, pretty?: int): java.lang.UnsupportedOperationException: must specify $class with an implementation of interface net.sf.json.JSON

So next I tried:

def data = readJSON text: '{}'
data.a = "test: ${myVar}"
writeJSON(file: 'message1.json', json: data, pretty: 4)

Now the build passes, but the content of the file looks like:

{
     "a":     {

        "bytes":         [

            114,

            101,

            108,

            101,

            97,

            115,

            101

            50

        ],

        "strings":         [

            "test: ",

            ""

        ],

        "valueCount": 1,

        "values": ["v1.0.2"]

    }
}

Whereas my intention was {"a": "test: v1.0.2"}

My end goal is that I want to dynamically construct a JSON object, set some properties with some dynamic data and then write the JSON file.

Is there some syntax that can be used to assign the values as strings, rather than some bytes.


回答1:


It seems one solution to this is changing the code that adds to the map to specify as String:

def data = readJSON text: '{}'
data.a = "test: ${myVar}" as String
writeJSON(file: 'message1.json', json: data, pretty: 4)


来源:https://stackoverflow.com/questions/53337109/jenkinsfile-pipeline-construct-json-object-and-write-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!