10#include <QJsonDocument>
18void writeData(
const QString &filename,
const QByteArray &data) {
19 QFile jsonFile(filename);
21 if (!jsonFile.open(QFile::WriteOnly)) {
22 throw std::invalid_argument(
"Could not open file at " + filename.toStdString());
25 if (jsonFile.write(data) == -1) {
26 throw std::runtime_error(
"Failed to write data to " + filename.toStdString());
33 auto filenameString = filename.toStdString();
34 if (filenameString.find_last_of(
".") == std::string::npos ||
35 filenameString.substr(filenameString.find_last_of(
".") + 1) != std::string(
"json")) {
39 QJsonDocument jsonDocument(QJsonObject::fromVariantMap(map));
40 writeData(filename, jsonDocument.toJson());
49 if (!file.open(QFile::ReadOnly)) {
50 throw std::invalid_argument(
"Cannot open file at: " + filename.toStdString());
54 QTextStream text(&file);
56 jsonString = text.readAll();
63 QByteArray jsonByteArray = jsonString.toLocal8Bit();
65 auto jsonDoc = QJsonDocument::fromJson(jsonByteArray);
66 if (jsonDoc.isNull()) {
67 throw std::runtime_error(
"Failed to create JSON doc.");
69 if (!jsonDoc.isObject()) {
70 throw std::runtime_error(
"JSON is not an object.");
73 QJsonObject jsonObj = jsonDoc.object();
74 if (jsonObj.isEmpty()) {
75 throw std::runtime_error(
"JSON object is empty.");
78 return jsonObj.toVariantMap();
void EXPORT_OPT_MANTIDQT_COMMON saveJSONToFile(QString &filename, const QMap< QString, QVariant > &map)
QMap< QString, QVariant > EXPORT_OPT_MANTIDQT_COMMON loadJSONFromString(const QString &jsonString)
QMap< QString, QVariant > EXPORT_OPT_MANTIDQT_COMMON loadJSONFromFile(const QString &filename)