1

The following text is a bit of std::string text that is generated by another app (I do not have control of what the app sends me). I have tried for days to get this converted into a QJsonArray and cannot figure this out. I am using C++ within QT. Does anyone have a bit of direction or sample C++ code that could solve this?

{
  "saved_mik_yous": {

    "2120ce2d-a5b1-49b8-8384-3781b7b2d73b": {
      "name": null,
      "id": "2120ce2d-a5b1-49b8-8384-3781b7b2d73b",
      "start": 1565288936.1127193,
      "end": 1565289128.1236603,
      "mixxer": 128.567505,
      "mik_source": "algo"
    },
    "bf855c0d-a71d-42ea-b3ef-7cbe0e2c7a3d": {
      "name": null,
      "id": "bf855c0d-a71d-42ea-b3ef-7cbe0e2c7a3d",
      "start": 1565301673.4609745,
      "end": 1565301832.665656,
      "mixxer": 308.485107,
      "mik_source": "algo"
    }
  },
  "mik_you_state": "completed"
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • It would help if you would show what you have already tried that is not working for you. What do you want the output to look like? But offhand, it is not surprising that you are having trouble getting this data into an array, when this data does not *represent* an array to begin with. JSON arrays are delimited with `[ ]` square braces, but there are no such characters in this data, everything is using `{ }` curly braces instead, which denote objects, not arrays. If `"saved_mik_yous"` is meant to be an array of objects, this data is not designed properly to accomplish that. – Remy Lebeau Jul 18 '22 at 21:40
  • Remy, That is a good comment, however, everything I have tried would have make "War and Peace" look like a comic book. :) – NotAChemist Jul 20 '22 at 19:04

1 Answers1

0

All you have to do is this:

QJsonDocument doc = QJsonDocument::fromJson(QByteArray::fromStdString(str));

Then, you can access the values for the keys for example as:

doc["saved_mik_yous"]

And so on.

Mind you, the json you are showing seems to be an object rather than an array since it contains key-value pairs rather than a list of elements inside square brackets. So, whilst it does not matter when you are converting the std::string into a QJsonDocument, you need to access the values by keys rather than indices.

If you are getting dynamic json which can be either an array or object, you can always check for the type with isArray() or isObject() to convert it to the right type.

László Papp
  • 51,870
  • 39
  • 111
  • 135