Move JSON helpers to lib

This commit is contained in:
WarmUpTill
2025-04-17 11:51:00 +02:00
committed by WarmUpTill
parent 7c4c0056ce
commit 5568f92ad0
13 changed files with 64 additions and 58 deletions

View File

@@ -0,0 +1,60 @@
#include "json-helpers.hpp"
#include <nlohmann/json.hpp>
#include <QJsonDocument>
namespace advss {
QString FormatJsonString(std::string s)
{
return FormatJsonString(QString::fromStdString(s));
}
QString FormatJsonString(QString json)
{
QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
if (doc.isNull()) {
return "";
}
return QString::fromUtf8(doc.toJson(QJsonDocument::Indented));
}
bool MatchJson(const std::string &json1, const std::string &json2,
const RegexConfig &regex)
{
auto j1 = FormatJsonString(json1).toStdString();
auto j2 = FormatJsonString(json2).toStdString();
if (j1.empty()) {
j1 = json1;
}
if (j2.empty()) {
j2 = json2;
}
if (regex.Enabled()) {
return regex.Matches(j1, j2);
}
return j1 == j2;
}
std::optional<std::string> GetJsonField(const std::string &jsonStr,
const std::string &fieldToExtract)
{
try {
nlohmann::json json = nlohmann::json::parse(jsonStr);
auto it = json.find(fieldToExtract);
if (it == json.end()) {
return {};
}
if (it->is_string()) {
return it->get<std::string>();
}
return it->dump();
} catch (const nlohmann::json::exception &) {
return {};
}
return {};
}
} // namespace advss

View File

@@ -0,0 +1,17 @@
#pragma once
#include "export-symbol-helper.hpp"
#include "regex-config.hpp"
#include <QString>
#include <string>
namespace advss {
EXPORT QString FormatJsonString(std::string);
EXPORT QString FormatJsonString(QString);
EXPORT bool MatchJson(const std::string &json1, const std::string &json2,
const RegexConfig &regex);
EXPORT std::optional<std::string> GetJsonField(const std::string &json,
const std::string &id);
} // namespace advss

View File

@@ -1,6 +1,5 @@
#include "utility.hpp"
#include <nlohmann/json.hpp>
#include <QTextStream>
#include <sstream>
@@ -28,25 +27,6 @@ bool ReplaceAll(std::string &str, const std::string &from,
return somethingWasReplaced;
}
std::optional<std::string> GetJsonField(const std::string &jsonStr,
const std::string &fieldToExtract)
{
try {
nlohmann::json json = nlohmann::json::parse(jsonStr);
auto it = json.find(fieldToExtract);
if (it == json.end()) {
return {};
}
if (it->is_string()) {
return it->get<std::string>();
}
return it->dump();
} catch (const nlohmann::json::exception &) {
return {};
}
return {};
}
bool CompareIgnoringLineEnding(QString &s1, QString &s2)
{
// Let QT deal with different types of lineendings

View File

@@ -15,8 +15,6 @@ EXPORT std::pair<int, int> GetCursorPos();
bool ReplaceAll(std::string &str, const std::string &from,
const std::string &to);
EXPORT std::optional<std::string> GetJsonField(const std::string &json,
const std::string &id);
EXPORT bool CompareIgnoringLineEnding(QString &s1, QString &s2);
std::string ToString(double value);