rapidjson icon indicating copy to clipboard operation
rapidjson copied to clipboard

Get char offset of rapidjson::Value inside json string

Open johnfranklinrickard opened this issue 1 year ago • 3 comments

I somehow missed it in the docs/implementation or I am unable to find it. We currently get json input as string, parse it via rapidjson::GenericDocument::ParseInsitu, and iterate over the elements. In the case of an error (or other reasons) we would like to map a rapidjson::Value to the char offset/line in the original json string/file. Is there a way to do this for rapidjson::Value's? If not, is there some other Parsing Model in rapidjson which would support this feature in some kind of way?

johnfranklinrickard avatar Nov 13 '24 13:11 johnfranklinrickard

In document.h:

    template <unsigned parseFlags>
    GenericDocument& ParseInsitu(Ch* str) {
        GenericInsituStringStream<Encoding> s(str);
        return ParseStream<parseFlags | kParseInsituFlag>(s);
    }

You can create the GenericInsituStringStream yourself and pass to GenericDocument::ParseStream, and then using GenericInsituStringStream::Tell() to get the position when fail. However, the position is not represented in line/column. You may code a new stream class that counts line/column.

miloyip avatar Nov 13 '24 14:11 miloyip

Ah sorry, I accidentally remove too much detail before posting it. But thank you already for the quick answers!

The parsing operation passes, and everything is fine from a json formatting/parsing perspective. But AFTER the parsing is done and passes, we look through the values and see some value greater X (which we want to alert someone that this is an error). Is there a way to get the offset of the actual rapidjson::Value object to the initial string/file?

johnfranklinrickard avatar Nov 13 '24 14:11 johnfranklinrickard

Currently no. You may consider using JSON schema in RapidJSON to validate the document and it will provide a JSON path for addressing the problem (although not in terms of line/column).

miloyip avatar Nov 14 '24 11:11 miloyip