3

I want to add more than one QJsonObject to a QJsonDocument. Is this possible?

It should look like this:

[
    {
        "objID": "obj1"
        //... Some other parameter
    },
    {
        "objID": "obj2"
        //...Some other parameter
    }
]

I tried this:

QJsonDocument(obj1).toJson(QJsonDocument::Compact);
QJsonDocument(obj2).toJson(QJsonDocument::Compact);

But it produces invalid JSON.

Azeem
  • 11,148
  • 4
  • 27
  • 40
Matthias
  • 461
  • 7
  • 24
  • I want to write Json file in below format. Is it possible? { { "objID": "obj1" //... Some other parameter }, { "objID": "obj2" //...Some other parameter } } – AB Bolim Mar 16 '19 at 05:38

1 Answers1

8

A JSON document has only one root value. In the example you gave, that value is an array, which contains two objects

To get that in Qt, you'd say:

QJsonArray array;
array << obj1;
array << obj2;
QJsonDocument(array).toJson(QJsonDocument::Compact);
puetzk
  • 10,534
  • 3
  • 28
  • 32
  • I want to write Json file in below format. Is it possible? `{ { "objID": "obj1" //... Some other parameter }, { "objID": "obj2" //...Some other parameter } }` – AB Bolim Mar 15 '19 at 12:38
  • That is not (valid) JSON; the {} means objects, which have to be { name: value, ...}. You could get [ { "objID": "obj1" //... Some other parameter }, { "objID": "obj2" //...Some other parameter } ], which would be an array of objects. – puetzk Mar 20 '19 at 22:16
  • Its a valid Json file. Json file may contain JArray, JObject or both. You can refer [this](https://stackoverflow.com/questions/55193946/how-i-can-add-more-than-one-qjsonobject-to-a-qjsondocument-qt) for more info. – AB Bolim Mar 27 '19 at 06:39
  • That one is valid: it has key names. Jobject has to be { name1: value1, name2: value2 }. Theirs has placeholder names "Obj1", "Obj2", and meets this. Yours asked for { value1, value2 }, which is not valid. – puetzk Apr 01 '19 at 14:34
  • I haven't ask for { value1, value2 } ? It may be you misunderstood my problem. – AB Bolim Apr 02 '19 at 07:07