I am a java fresher and I went to an interview recently. They asked a question which was something like: Set up Groovy, test whether a sample json file is valid or not. If it is valid, run the json file. If it is not, print "File is not valid". If file is not found, print "file not found". I was given 2 hours time to do it and I could use the internet.
As I had no idea what groovy was or json was, I searched it and set up groovy but could not obtain the output in two hours. What should I have written? I tried some code but I am sure that it was wrong.
You can use file.exists()
to check if the file exists on the filesystem and file.canRead()
to check if it can be read by the application. Then use JSONSlurper
to parse the file and catch JSONException
if the json is invalid:
import groovy.json.*
def filePath = "/tmp/file.json"
def file = new File(filePath)
assert file.exists() : "file not found"
assert file.canRead() : "file cannot be read"
def jsonSlurper = new JsonSlurper()
def object
try {
object = jsonSlurper.parse(file)
} catch (JsonException e) {
println "File is not valid"
throw e
}
println object
To pass the file path argument from the command line, replace def filePath = "/tmp/file.json"
with
assert args.size == 1 : "missing file to parse"
def filePath = args[0]
and execute on the command line groovy parse.groovy /tmp/file.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With