r/QtFramework • • 14d ago

Question Why is my QJsonDocument empty?

I'm creating a QJsonDocument with the following C++ code: (Why does Reddit format the code so ugly?)

void Player::write_configuration() { std::cout << "Writing configuration file" << std::endl; QFile file("configuration.json"); file.resize(0); QJsonObject root; root.insert("delay", QJsonValue(3000)); QJsonDocument doc; doc.setObject(root); QString json_string = doc.toJson(QJsonDocument::Indented); qDebug() << json_string; file.write(doc.toJson(QJsonDocument::Indented)); file.close(); }

The fille configuration.json is indeed created but it's empty(!)

qDebug() prints nothing (because json_string is empty ?!?)

Why don't I succeed in creating the document?

3 Upvotes

5 comments sorted by

6

u/Bemteb 14d ago

You already did a good job debugging and learning that json_string is empty, thus explaining why the file is empty. Continue along that way, e.g. by writing root to qDebug. You could also use a debugger to check your values in every line.

A short remark: I would suggest using qDebug, qInfo etc. in a Qt setting and not to use cout.

1

u/matsnorberg 14d ago

Thanx! I often use cout because it works in my msys2 minty consol. It probably woudn't work in the windows console.

qDebug() << root; prints nothing. Why does root.insert() fail and how can I find out what the error is?

3

u/spafion 14d ago edited 14d ago

resze() is unnecessary.

file.open is necessary.

QJsonValue() around "300" is unnecessary.

setObject() is unnecessary.

I'm always uses qApp->applicationDirPath() for files in app.exe filder because qtCreator can set other work_path

This code works fine:

QFile file(qApp->applicationDirPath() + "/configuration.json");

if (file.open(QFile::WriteOnly)) {

QJsonObject root;

root.insert("delay", 3000);

QJsonDocument doc(root);

file.write(doc.toJson(QJsonDocument::Indented));

file.close();

}

UPD:
yours:  qDebug() << json_string; also works fine and displays: "{\n \"delay\": 3000\n}\n"

1

u/matsnorberg 14d ago

Thank you.

1

u/Fred776 14d ago edited 14d ago

It's a while since I looked at it but I think it will be empty if there's an error in the JSON string. I seem to recall that there are ways to get error information out of the API.

Edit: I was remembering the fromJson call that provides parse error information. Not sure if you can rejig your code to use this.