2

I need to run the groovy scripts below to build a JSON template. The issue i am running into is that the integer in the template is surrounded in quotes. Stripping out the quotes from the variables treats it like a string.

cat port.txt
1001

Here is my JSON builder script

def test = new groovy.json.JsonBuilder()
   test {
    ports new File('ports.txt').readLines()*.trim().collect { p ->
        [name: "$p-tcp", protocol: "TCP", port: "$p", targetPort: "$p"]
    }
}
println test.toPrettyString()

When i run it, it spits out the following:

{
"ports": [
    {
        "name": "1001-tcp",
        "protocol": "TCP",
        "port": "1001",
        "targetPort": "1001"
    }
]
}

However I want it to do strip out the quotes for the ports and targetPorts like so

{
"ports": [
    {
        "name": "1001-tcp",
        "protocol": "TCP",
        "port": 1001,
        "targetPort": 1001
    }
]
}

Any clue on how to accomplish this is much appreciated.

crusadecoder
  • 651
  • 1
  • 11
  • 26
  • Possible duplicate of [How to construct json using JsonBuilder with key having the name of a variable and value having its value?](https://stackoverflow.com/questions/19225600/how-to-construct-json-using-jsonbuilder-with-key-having-the-name-of-a-variable-a) – Dale K Jan 30 '19 at 02:15
  • @NathanHughes Can you please advise how to do that? I am still a beginner with groovy. – crusadecoder Jan 30 '19 at 02:25
  • Change `port: "$p"` to `port: Integer.parseInt(p)` – tim_yates Jan 30 '19 at 07:04

1 Answers1

1

If you expect the ports.txt file to always contain just integers, then you can convert the read lines to integers before collecting them. Without even trimming the strings. Also, note removed quotes around p in port: ant targetPort:

def test = new JsonBuilder()
test {
    ports new File('ports.txt').readLines()*.toInteger().collect { p ->
        [name: "$p-tcp", protocol: "TCP", port: p, targetPort: p]
    }
}
println test.toPrettyString()

Output:

{
    "ports": [
        {
            "name": "1001-tcp",
            "protocol": "TCP",
            "port": 1001,
            "targetPort": 1001
        }
    ]
}
Dmitry Khamitov
  • 3,061
  • 13
  • 21