Answer the question
In order to leave comments, you need to log in
How to make it easier to access json nested object in Qt?
There is this json
{
"firstName": "Иван",
"lastName": "Иванов",
"address": {
"streetAddress": "Московское ш., 101, кв.101",
"city": "Ленинград",
"postalCode": 101101
},
"phoneNumbers": [
"812 123-1234",
"916 123-4567"
]
}
QFile j_file( "file.json" );
if( !j_file.open( QIODevice::ReadOnly | QIODevice::Text ) )
qDebug() << "Err open file";
QJsonDocument j_doc = QJsonDocument::fromJson( j_file.readAll() );
QJsonObject j_obj = j_doc.object();
QJsonValue j_val = "Piter";
QJsonObject jo(j_obj["address"].toObject());
jo["city"] = j_val;
j_obj["address"] = jo;
Answer the question
In order to leave comments, you need to log in
I found a function that allows you to easily go to any depth and modify the values.
void parseJson::modifyJsonValue(QJsonObject &obj, const QString &path, const QJsonValue &newValue)
{
const int indexOfDot = path.indexOf( '.' );
qDebug() << indexOfDot;
const QString propertyName = path.left( indexOfDot );
qDebug() << propertyName;
const QString subPath = indexOfDot > 0 ? path.mid(indexOfDot + 1) : QString();
QJsonValue subValue = obj[ propertyName ];
if(subPath.isEmpty()) {
subValue = newValue;
}
else {
QJsonObject obj = subValue.toObject();
modifyJsonValue(obj,subPath,newValue);
subValue = obj;
}
obj[propertyName] = subValue;
}
void modifyJsonValue(QJsonDocument& doc, const QString& path, const QJsonValue& newValue) {
QJsonObject obj = doc.object();
modifyJsonValue(obj,path,newValue);
doc = QJsonDocument(obj);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question