Search code examples
jsonlinuxvariablesgroovyyaml

How to define a variable within a JSON file and use it within JSON file


I'm trying to find if JSON file supports defining variables and using them within that JSON file?

{
    "artifactory_repo": "toplevel_virtual_NonSnapshot",
    "definedVariable1": "INSTANCE1",
    "passedVariable2":  "${passedFromOutside}",
    "products": [ 
              { "name": "product_${definedVariable1}_common",
                "version": "1.1.0"
              },
              { "name": "product_{{passedVariable2}}_common",
                "version": 1.5.1
              }
     ]
}  

I know YAML files allow this but now sure if JSON file allows this behavior or not. My plan is that a user will pass "definedVariable" value from Jenkins and I'll create a target JSON file (after substi


Solution

  • You can use Groovy's SimpleTemplateEngine to do the trick:

    def json = '''\
    {
        "artifactory_repo": "toplevel_virtual_NonSnapshot",
        "definedVariable1": "INSTANCE1",
        "passedVariable2":  "${passedFromOutside}",
        "products": [ 
                  { "name": "product_${definedVariable1}_common",
                    "version": "1.1.0"
                  },
                  { "name": "product_${passedVariable2}_common",
                    "version": 1.5.1
                  }
         ]
    }'''
    
    def engine = new groovy.text.SimpleTemplateEngine()
    def binding = [ passedFromOutside:"Grace", definedVariable1:42, passedVariable2:true ]
    String res = engine.createTemplate json make binding toString()
    

    returns

    {
        "artifactory_repo": "toplevel_virtual_NonSnapshot",
        "definedVariable1": "INSTANCE1",
        "passedVariable2":  "Grace",
        "products": [ 
                  { "name": "product_42_common",
                    "version": "1.1.0"
                  },
                  { "name": "product_true_common",
                    "version": 1.5.1
                  }
         ]
    }
    

    Then you can dump the output straight into the file like:

    file( 'some/file.json' ).text = res