How Can We Help?
< Back
You are here:
Print

JSON files with comments via Groovy

It is very easy to work with JSON strings and files in Groovy. One key limitation of JSON is that there is no mechanism for including comments in JSON files. The only officially supported way to include comments in JSON files is to include the comments in the actual data.

In some scenarios, comments are invaluable. For example, if you define a JSON file that provides some type of configuration data, comments enhance the results.

Even though the JSON standard doesn’t support comments, it turned out to be quite easy to write Groovy code that loads JSON from a file with comment support. The goal was to allow you to flag comment lines in the file. Any line that starts with ‘#’ or ‘//’ is considered to be a comment line. When the code loads and parses the JSON file, it ignores all comment lines.

This is an example file with comments.

# this is a comment
{
  "template": {
    "applicationName": "MyApplication",
    "teamName": "MyTeam",
    "components": [
      {
        "name": "sample_ear_component",
// This is a comment as well		
        "cluster": "sample_cluster"
      }
    ]
  }
}

The following code is a Groovy function which loads and parses a json file and ignores comment lines as it does so. It return the parsed JSON content.

/**
 * Reads a JSON file which has comments.  A comment
 * is any line that starts with '//' or '#'.  All comment lines
 * are ignored when reading and parsing the file.
 */
def readCommentedJsonFile( File file ) {

	def lines = file.readLines()
	def bodyWithoutComments = ''

	lines.each { String line ->
		if (line.startsWith('//') || line.startsWith('#')) {
			// This is a comment line, ignore it
		} else {
			bodyWithoutComments = bodyWithoutComments + line + '\n'
		}
	}
	
	return new groovy.json.JsonSlurper().parseText(bodyWithoutComments)
}

For example, you can use the following example code to read the earlier example file (as ‘example.json’) and see the value of the applicationName. This also displays the loaded data as a JSON string.

def data = readCommentedJsonFile( new File("example.json") )
println "data.template.applicationName is ${data.template.applicationName}"
println groovy.json.JsonOutput.toJson( data ) 

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents