json Groovy 文件检查

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39262999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:35:37  来源:igfitidea点击:

Groovy file check

jsongroovy

提问by krisnis

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.

我是 Java 新生,最近去面试了。他们问了一个类似的问题:设置 Groovy,测试示例 json 文件是否有效。如果有效,则运行 json 文件。如果不是,则打印“文件无效”。如果找不到文件,则打印“找不到文件”。我有 2 小时的时间来做这件事,我可以使用互联网。

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.

由于我不知道 groovy 是什么或 json 是什么,我搜索它并设置了 groovy 但无法在两个小时内获得输出。我应该写什么?我尝试了一些代码,但我确定它是错误的。

回答by Gergely Toth

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 JSONSlurperto parse the file and catch JSONExceptionif the json is invalid:

您可以使用file.exists()来检查文件系统上是否存在该文件,并file.canRead()检查应用程序是否可以读取该文件。然后用于JSONSlurper解析文件并捕获JSONExceptionjson 是否无效:

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

要从命令行传递文件路径参数,请替换def filePath = "/tmp/file.json"

assert args.size == 1 : "missing file to parse"
def filePath = args[0]

and execute on the command line groovy parse.groovy /tmp/file.json

并在命令行上执行 groovy parse.groovy /tmp/file.json