I want to parse and validate (custom) JSON configuration files in Go. I would like to be able to parse the file in a structure and verify that:
- there are no unexpected keys in the JSON file (in particular, to detect typos)
- there are certain keys and have non-empty values
In the case of a failed check (or in the case of a syntax error) I want to print an error message for the user, which explains in as much detail as possible where the error occurred in the file (for example, indicating 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 JSON, which returns an error in case of an unexpected key, but does not report a position.
To check for non-empty values, I could use the existing validation library, but I did not see any messages display detailed error messages. Alternatively, I could write my own code that checks the data returned by the built-in JSON parser, but it would be nice if there was a general way.
Is there an easy way to get the desired behavior?
source
share