0

I am creating json file using echo statement ,it works fine as long as static string.

echo '
{
    "common": {
        "baseUri": "https://mycompany.com",
        "ipPrefix": "192.23.4.",
     }
}' > test.json

But when I need to interpolate string inside echo command it is not working.

 echo '
    {
        "common": {
            "baseUri": "$company_name",
            "ipPrefix": "192.23.4.",
         }
    }' > test.json

How to create json file in jenkins with parameter values substituted?

Samselvaprabu
  • 16,830
  • 32
  • 144
  • 230
  • Does this answer your question? [Create JSON strings from Groovy variables in Jenkins Pipeline](https://stackoverflow.com/questions/44707265/create-json-strings-from-groovy-variables-in-jenkins-pipeline) – 0stone0 Nov 30 '21 at 14:05
  • Regarding bash only, without considering jenkins/groovy : you are using single quotes, so no parameter expansion – Aserre Nov 30 '21 at 14:26
  • Does this answer your question? [When should I wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-should-i-wrap-quotes-around-a-shell-variable) – Aserre Nov 30 '21 at 14:27

2 Answers2

1

The issue is due to the quotes as suggested in the comments.

Script below should work for you:

company_name="https://mycompany.com"
echo '{
     "common": {
          "baseUri": "'$company_name'",
          "ipPrefix": "192.23.4."
     }
}' > test.json

Output:

{
     "common": {
          "baseUri": "https://mycompany.com",
          "ipPrefix": "192.23.4."
     }
}

The value of any variable can’t be read by single quote ', since it only represents the literal value of all characters within it. To get the value of company_name we need to end the single quotes, then add the variable and start single quotes again.

Parameter expansion
Quoting

0

With pipeline utility steps plugin, you can write any groovy map straight to a JSON file:

def company_name = "http://mycompany.com/"
def map = [ 
    "common" : [ 
        "baseUri": company_name,
        "ipPrefix": "192.23.4."
    ]
]

writeJSON json: map, file: test.json
Rik Sportel
  • 2,661
  • 1
  • 14
  • 24