json: How to get position info or parser context with custom from_json() that may throw exceptions?

Sorry if the question is lame or was answered before (couldn’t find anything similar in the issues history).

Is it possible to get a position info or, better, a typical json::exception with a context where the “parsing” failed, for any exceptions thrown inside my custom from_json() for third party classes that may throw errors on their from_string() builder functions?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Comments: 19 (10 by maintainers)

Most upvoted comments

FYI: I am trying to fix this issue in https://github.com/nlohmann/json/pull/2562. Any help would be greatly appreciated!

I wish it would be that easy… What I could think of is the following:

  • Add a pointer to basic_json to link the parent of the value. Thereby, the null in [null] could “know” that it is part of an array. For this, all constructors need to be adjusted to set that value.
  • If an error occurs at some value, we can go up the parent chain and generate some diagnostic information like a JSON pointer to the child value. Then you could identify a value with /foo/bar/1, so the user can understand which value has the wrong type.
  • Maybe (!), we could also add the parse location to values.

All this should be hidden behind some preprocessor macro such that you will never pay for the overhead (1 pointer, 2 integers) if you don’t want to.