Search code examples
qtqt5qwebelement

Encoding a QString in JSON


I'm trying to encode a QString into a JSON string, so that I can inject it safely via QWebFrame::evaluateJavaScript(QString("o.text = %1;").arg(???)).

For example, in php using the function json_encode

echo json_encode('HELLO "me"');

The output would be

"HELLO \"me\""

This is the internal representation of the string, within the Json object.

In the same way, using Qt, how can I retrieve the internal representation of a string, as it would be encoded as a value, within a Json formatted string?


Solution

  • It's really not that difficult. Start by building up the structure with QJsonObjects

    QJsonObject obj;
    obj.insert("tag1", QString("Some text"));
    

    Then use QDocument to get a string in Json format

    QJsonDocument doc(obj);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    
    QString jsonString(data);
    

    This will produce a string, in the form of: -

    { "tag1" : "Some Text" }

    Separate items into a list, splitting on ':'

    QStringList items = jsonString.split(':', QString::SkipEmptyParts);
    

    There should be 2 items in the list, the second being the value section of the Json string

    "Some Test"}

    Remove the final '}'

    QString value = items[1].remove('}');

    Of-course, you will need to do error checking and be aware that if you have a ':' or '}' in the original string, then you'll need to check for them first.