duansaxf095988 2016-08-11 15:28
浏览 547

验证JSON并显示错误位置

I want to parse and validate (custom) JSON configuration files within Go. I would like to be able to parse the file into a struct and validate that:

  1. no unexpected keys are present in the JSON file (in particular to detect typos)
  2. certain keys are present and have non-empty values

In case the validation fails (or in case of a syntax error), I want to print an error message to the user that explains as detailed as possible where in the file the error happened (e.g. by stating the line number if possible).

The JSON parser built into Go seems to just silently ignore unexpected keys. I also tried using jsonpb (Protobuf) to deserialize the JSON, which returns an error in case of an unexpected key, but does not report the position.

To check for non-empty values, I could use an existing validation library, but I haven't seen any does reports detailed error messages. Alternatively, I could write custom code that validates the data returned by the built-in JSON parser, but it would be nice if there was a generic way.

Is there a simple way to get the desired behaviour?

  • 写回答

1条回答 默认 最新

  • dongwuli5105 2016-08-11 15:34
    关注

    Have you looked at JSON schema?

    JSON Schema describes your JSON data format.

    I believe it is in Draft stage, but a lot of languages have validation libraries. Here's a Go implementation:

    评论

报告相同问题?

悬赏问题

  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题