c++jsonqtqjsondocument

Why is QJsonDocument::fromJson failing to parse a simple value?


QJsonParseError err;
auto doc = QJsonDocument::fromJson ("true", err);
qInfo () << doc.isNull () << err;

Output is: true 5, which indicates a parsing error, and "5" is QJsonParseError::IllegalValue.

The same happens with any simple value tested (null, true, false, numbers and strings).

Why is it an error, although the parsed JSON is valid?


Solution

  • Yes, the JSON value you are testing with is technically valid, per the JSON standards. However, Qt's documentation implies that QJsonDocument is more limited than the JSON standard allows:

    JSON Support in Qt

    A valid JSON document is either an array or an object, so a document always starts with a square or curly bracket.

    Which means QJsonDocument::fromJson() simply can't parse simple values, as you are attempting to do. It can only parse values that are inside of arrays [...] or objects {...}, eg:

    auto doc = QJsonDocument::fromJson ("[true]", err);
    
    auto doc = QJsonDocument::fromJson ("{\"value\":true}", err);