1

I have a QString that I need to insert it to a QJsonArray. The problem is that the string is inserrted as it is and the escape sequences doesnot work.

    QString fmt = QString("{\n \"%1\":\"%2\"\n}").arg(id,name);
    QJsonValue qjv(fmt);
    labellist.insert(lSize, qjv);

Here, the qstring is populated with the values from "id" and "name" (these are also QString) and then inserted to qjsonarray. The labellist here is a QJsonArray. The inputs to the QString are say for example "55" and "ggg". When I print the qstring like

    qDebug().noquote() << fmt;

it gives me

    {
     "55":"ggg"
    }

but if I insert it to the labellist and print the labellist it gives:

    QJsonArray([{"121":"fuu"},{"122":"cat"},{"123":"dog"},"{\n \"55\":\"ggg\"\n}"])

The format of the QJsonvalues in the above array is lost.

How to decode the string to preserve the format and make the escape sequences work?

scopchanov
  • 7,966
  • 10
  • 40
  • 68
  • Why do you insert formatting characters? You don't need to do that. That's why `QJson*` classes are for. They do it for you. – vahancho Nov 03 '17 at 07:58

1 Answers1

1

I would use QJsonDocument static method fromJson(), like this:

  QString fmt = QString("{\n \"%1\":\"%2\"\n}").arg("id","name");

  QJsonDocument doc = QJsonDocument::fromJson(fmt.toLocal8Bit());
  QJsonObject obj = doc.object();

  QJsonArray array;
  array.append(obj);

  qDebug() << array;
p-a-o-l-o
  • 9,807
  • 2
  • 22
  • 35