Position info when decoding JSON?


I am decoding a largish file of JSON, and would like to give nice error messages. If I use a Json.Decode.Decoder there is no context describing the position within the JSON that could be used to help with this.

For example, I might like an error message like:

The field 'date' must be in ISO format (like 2020-01-30):

204|    someRecord : {
205|        date : 1234,
206|        ...

I think to do this, I would need to write a Parser for JSON from scratch. Never actually looked at the code, but I suspect that the String -> JSON part happens in javascript, and Elm works with the in-memory JSON after that.

If I can’t do that, perhaps an easier way might be to track the positional context through the structure of the JSON, to give an error message like this:

The field 'date' must be in ISO format (like 2020-01-30):

At 'someArray[5].someRecord.date', the value given is 1234, which is not in ISO format.

Any ideas how to accomplish this? Is there some transformation that can be built on top of a Decoder to always give this context, or perhaps even a package that already does this?

Have you seen https://package.elm-lang.org/packages/zwilias/json-decode-exploration/latest/?
I have not used it, but I believe it gives you the tools to do what you want.

Yes, just looking at that. I think it would give me the descriptive path solution ( someArray[5].someRecord.someField ).

I am also looking at this one, and wondering if it could be upgraded to Parser.Advanced and report line numbers:


This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.