doubi4491 2018-02-13 11:26 采纳率: 0%
浏览 377

使用Avro Schema验证Json文件

I'm trying to check if a Json string matches an Avro schema. I don't care about doing serialization of the data, just getting a bool result of isValidJson=true/false. I'll go with every golang library. I've tried to write something with this goavro lib, but it didn't work for me, maybe because I'm new to go like.

Desired pseudo code:

func main() {
    avroSchema := 
    `{"type":"record","name":"raw","namespace":"events","fields":[{"name":"my_int","type":["null","int"],"default":null},{"name":"my_string","type":["null","string"],"default":"null"},{"name":"my_string2","type":null}]}`
    jsonString := `{"my_int": 3, "my_string": "foo", "my_string2": null}`
    ok ;= isValidJson(jsonString, avroSchema)
}

Any idea how to implement the isValidJson(..) method?

  • 写回答

1条回答 默认 最新

  • dqnz43863 2018-02-13 12:47
    关注

    Your schema json is invalid, it's missing the terminating }, so goavro.NewCodec returns an error.

    Then your json string definitely doesn't match the schema, the json values must be a {type: value}.

    You can use the following corrected schema and example string to validate it.

    func main() {
      avroSchema := `
    { 
       "type":"record",
       "name":"raw",
       "namespace":"events",
       "fields":[
          {
             "name":"my_int",
             "type":[
                "null",
                "int"
             ],
             "default":null
          },
          {
             "name":"my_string",
             "type":[
                "null",
                "string"
             ],
             "default":null
          },
          {
             "name":"my_string2",
             "type":"null"
          }
       ]
    }`
      codec, err := goavro.NewCodec(avroSchema)
      if err != nil {
        log.Fatalf("Codec error: %v", err)
      }
    
      jsonString := `{"my_int": {"int":3}, "my_string": {"string":"foo"}, "my_string2": null}`
    
      decoded, _, err := codec.NativeFromTextual([]byte(jsonString))
      if err != nil { 
        log.Fatalf("NativeFromTextual error: %v", err)
      } 
      log.Println("Decoded:", decoded)
    } 
    

    This prints:

    Decoded: map[my_int:map[int:3] my_string:map[string:foo] my_string2:]

    评论

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料