Encoding a QString in JSON

2.2k views Asked by At

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?

2

There are 2 answers

5
TheDarkKnight On BEST ANSWER

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.

0
Zmey On

Original answer doesn't handle : and } inside of string correctly. A similar approach using array which requires only stripping []:

QString encodeJsonStringLiteral(const QString &value)
{
    return QString(
                QJsonDocument(
                    QJsonArray() << value
                ).toJson(QJsonDocument::Compact)
           ).mid(1).chopped(1);
}

ab"c'd becomes "ab\"c'd"

Or, if you don't need double quotes around the string, replace with .mid(2).chopped(2)