nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
41.33k stars 6.58k forks source link

Fix examples/json_lines.cpp #4219

Closed mrgharabaghi closed 7 months ago

mrgharabaghi commented 7 months ago

The extra newline throws an exception.


Pull request checklist

Read the Contribution Guidelines for detailed information.

Please don't

nlohmann commented 7 months ago

What is your exact error message? The code of docs/examples/json_lines.cpp compiles fine as-is.

gregmarr commented 7 months ago

The original report says it throws an exception, so I assume this is a runtime error, and the error is on the json::parse of an empty line after the last valid line.

mrgharabaghi commented 7 months ago

As gregmarr said, this is a runtime error. Sorry, there is no problem with this example. As you can see on the below snippet, I put 4 extra whitespaces before )"; on 6th line. I think this exception is related to the <nlohmann/json.hpp>'s core. Should I have to open a Bug Report issue?

int main() {
    input << R"({"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]}
             {"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]}
             {"name": "May", "wins": []}
             {"name": "Deloise", "wins": [["three of a kind", "5♣"]]} 
    )";

    try
    {
        while (std::getline(input, line))
        {
            std::cout << json::parse(line) << std::endl;
        }
    }
    catch (json::parse_error& ex)
    {
        std::cerr << "parse error at byte " << ex.byte << std::endl;
    }
}
{"name":"Gilbert","wins":[["straight","7ΓÖú"],["one pair","10ΓÖÑ"]]}
{"name":"Alexa","wins":[["two pair","4ΓÖá"],["two pair","9ΓÖá"]]}
{"name":"May","wins":[]}
{"name":"Deloise","wins":[["three of a kind","5ΓÖú"]]}
parse error at byte 5
nlohmann commented 7 months ago

Sorry: I meant I can compile and run the example as-is.

gregmarr commented 7 months ago

Sorry: I meant I can compile and run the example as-is.

I can confirm the error with the blank line at the end: https://www.godbolt.org/z/3hzGz75WE

And now it's gone. It was there a minute ago with the single newline at the end, but now it's not, it must have still been updating. It's only there with two or more newlines at the end.

gregmarr commented 7 months ago

As you can see on the below snippet, I put 4 extra whitespaces before )"; on 6th line.

Yeah, that's the source of the issue. You changed from having a newline at the end of the data, which is handled cleanly, to having whitespace after the final newline, which does not get handled cleanly. You'd need to strip leading whitespace from line before passing it to json::parse() if you wanted to support that.

nlohmann commented 7 months ago

Anything to do here then? And: if so, please create an PR for the develop branch and not the gh-pages.