1. QJsonValue findKey(const QString& key, const QJsonValue& value)
    2. {
    3. if (value.isObject()) {
    4. QJsonObject obj = value.toObject();
    5. if (obj.contains(key)) {
    6. return obj.value(key); // return 'early' if object contains key
    7. }
    8. for (const auto& value : obj) {
    9. QJsonValue recurse = findKey(key, value); // call itself, forwarding a value
    10. if (!recurse.isNull())
    11. return recurse; // value found, return 'early'
    12. }
    13. } else if (value.isArray()) {
    14. for (const auto& value : value.toArray()) {
    15. QJsonValue recurse = findKey(key, value);
    16. if (!recurse.isNull())
    17. return recurse;
    18. }
    19. }
    20. return QJsonValue(); // base case: a null value
    21. }
    22. int main(int argc, char *argv[])
    23. {
    24. QFile file(":/res/scratch.json"); // json stored in a qrc with /res/ prefix
    25. file.open(QIODevice::ReadOnly);
    26. if (!file.isOpen()) {
    27. qDebug() << "error: couldn't open scratch.json";
    28. return 0;
    29. }
    30. QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
    31. qDebug() << "value:" << findKey("treasure", doc.object());
    32. }

    scratch.json:

    1. {
    2. "deck": [
    3. "first mate",
    4. "sailor",
    5. "john muir"
    6. ],
    7. "cabin": [
    8. {
    9. "name": "lamp"
    10. },
    11. {
    12. "name": "treasure chest",
    13. "items": {
    14. "diamonds": 3,
    15. "silver": 5,
    16. "gold": 10,
    17. "safebox": {
    18. "treasure": "shiny"
    19. }
    20. }
    21. }
    22. ]
    23. }

    result:

    1. value: QJsonValue(string, "shiny")

    参考链接 https://stackoverflow.com/questions/56122822/is-there-a-way-find-a-key-in-the-whole-json-file-using-qjsonobject