【问题标题】:How to change values in a json file?如何更改json文件中的值?
【发布时间】:2020-07-26 11:30:43
【问题描述】:

我有以下 JSON 文件:

{
    "users":[
        {"nom":"123",
        "name":"John",
        "family":"ala",
        "cash":1000
    }
    ,{"nom":"456",
        "name":"Joe",
        "family":"ala",
        "cash":1000
    }
    ,{"nom":"131",
        "name":"David",
        "family":"ala",
        "cash":1000
    }]
}

我想换John的现金。

这就是我试图实现这一目标的方式:

 QFile f("file address ...");
     f.open(QIODevice::ReadOnly|QIODevice::Text|QIODevice::WriteOnly);
       QByteArray b=f.readAll();
       QJsonDocument d=QJsonDocument::fromJson(b);
       QJsonObject o=d.object();

       for (int i=0;i<o["users"].toArray().size();i++) {
          if(o["users"].toArray()[i].toObject()["name"].toString()=="John")
          o["users"].toArray()[i].toObject()["cash"].toInt()=2000;//error unable to assign
            }

但是,我收到以下错误:

错误:无法分配

如何解决这个问题?

【问题讨论】:

  • 使用 lib 并将字符串(反序列化)转换为 json 对象,您可以通过键、值、索引等轻松访问该对象
  • @ΦXocę웃Пepeúpaツ OP 正在使用 QJsonDocumentQJsonObject 做同样的事情。问题是,这是如何读取值,而不是如何写入。
  • @Lily,你可能想看看JSON Save Game Example
  • 提示:删除.toInt()

标签: c++ json qt


【解决方案1】:

原因

您收到错误消息,因为您试图为函数的返回值分配一个值(在本例中为QJsonValue::toInt)。

解决方案

将值分配给QJsonValue,如JSON Save Game Example 中所示:

void Character::write(QJsonObject &json) const
{
    json["name"] = mName;
    json["level"] = mLevel;
    json["classType"] = mClassType;
}

示例

这是我为您编写的示例,以演示如何更改您的代码以实现建议的解决方案:

#include <QApplication>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QFile file("data.json");

    if (file.open(QFile::ReadOnly | QFile::Text)) {
        QJsonObject json = QJsonDocument::fromJson(file.readAll()).object();
        QJsonArray users = json["users"].toArray();

        file.close();

        for (auto user : users) {
            QJsonObject userObj = user.toObject();

            if (userObj["name"].toString() == "John")
                userObj["cash"] = 2000;

            user = userObj;
        }

        qDebug() << users;
    }

    return a.exec();
}

结果

给定的示例产生以下结果:

QJsonArray([{"cash":2000,"family":"ala","name":"John","nom":"123"},{"cash":1000,"family":"ala","name":"Joe","nom":"456"},{"cash":1000,"family":"ala","name":"David","nom":"131"}])

请注意,Johncash 设置为 2000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2021-07-04
    • 2021-02-05
    • 1970-01-01
    • 2019-02-18
    相关资源
    最近更新 更多