简体   繁体   English

如何使用Avro架构验证JSON?

[英]How do I use an Avro schema to validate JSON?

I'd like to know the feasibility of using an Avro schema to validate JSON that comes into my app. 我想知道使用Avro架构验证进入我的应用程序的JSON的可行性。 In this post , Doug Cutting suggests using the jsontofrag tool that comes with the avro-tools jar. 这篇文章 ,道格切割建议使用jsontofrag自带的Avro的工具jar工具。 His example is a trivial one of a JSON "document" that is just a number: 他的例子是一个简单的JSON“文档”,它只是一个数字:

echo 2 | java -jar avro-tools.jar jsontofrag '"int"' - | java -jar avro-tools.jar fragtojson '"int"' - 

While this works, I'd like to know how to do it with a more interesting JSON doc. 虽然这有效,但我想知道如何使用更有趣的JSON文档。

When I try this with the example JSON doc and schema on the Avro website it fails, like so: 当我在Avro网站上使用示例JSON doc和schema尝试此操作时,它会失败,如下所示:

The Avro schema: Avro架构:

{"namespace": "example.avro",
 "type": "record",
 "name": "User",
 "fields": [
     {"name": "name", "type": "string"},
     {"name": "favorite_number",  "type": ["int", "null"]},
     {"name": "favorite_color", "type": ["string", "null"]}
 ]
}

Example JSON doc 示例JSON doc

{"name": "Ben",
 "favorite_number": 7,
 "favorite_color": "red"}

But when I try to do it with: 但当我尝试这样做时:

cat user.json | java -jar avro-tools.jar jsontofrag user.avsc - | java -jar avro-tools.jar fragtojson user.avsc -

It get this error (stack trace elided): 它得到此错误(堆栈跟踪省略):

Exception in thread "main" org.apache.avro.SchemaParseException: org.codehaus.jackson.JsonParseException: 
Unexpected character ('u' (code 117)): 
expected a valid value (number, String, array, object, 'true', 'false' or 'null') 
at [Source: java.io.StringReader@74dca977; line: 1, column: 2]

Any ideas on how to make this work? 关于如何使这项工作的任何想法? Or another way to use an Avro schema to validate JSON? 或者使用Avro架构验证JSON的另一种方法?

The usage (and backtrace) for the jsontofrag tool leaves much to be desired; jsontofrag工具的用法(和回溯)还有很多不足之处; what it means by "schema" is a literal schema string, not a filename containing a schema. “schema”的含义是文字架构字符串,而不是包含架构的文件名。 (Surprise!) The following tweak to your command worked for me: (惊喜!)以下对你命令的调整对我有用:

cat user.json | java -jar avro-tools.jar jsontofrag "`cat user.avsc`" - | java -jar avro-tools.jar fragtojson "`cat user.avsc`" -

Here I've used old-style backtics for command-substitution; 在这里,我使用旧式的背景来进行命令替换; the newer "$(cat user.avsc)" syntax also works in bash and probably in other modern(ish) shells. 较新的“$(cat user.avsc)”语法也适用于bash,也可能适用于其他现代(ish)shell。

fromjson is an alternative to jsontofrag that is perhaps easier and more straightforward. fromjsonfromjson的替代jsontofrag ,可能更简单,更直接。

java -jar avro-tools.jar fromjson --schema-file user.avsc user.json > user.avro

If the JSON is not valid, this will throw an Exception, so that is how one can use this to validate JSON. 如果JSON无效,则会抛出异常,因此可以使用它来验证JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM