Created
April 19, 2019 06:02
-
-
Save iamazeem/41af8322d71cbd35288cc6a24fb9b55c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://stackoverflow.com/a/55297349/7670262 | |
#include <QDebug> | |
#include <QJsonDocument> | |
#include <QJsonObject> | |
#include <QJsonArray> | |
int main() | |
{ | |
const auto data = R"({ "Name": "45", "Path": "C:\file.json" })"; | |
auto doc = QJsonDocument::fromJson( data ); | |
qDebug() << "BEFORE:\n\n" | |
<< qPrintable( doc.toJson( QJsonDocument::Indented ) ); | |
// Create an array and add objects | |
const auto obj1 = QJsonObject{ { "name", "abc" }, { "default", 11 } }; | |
const auto obj2 = QJsonObject{ { "name", "xyz" }, { "default", 22 } }; | |
auto obj = doc.object(); | |
obj.insert( "array", QJsonArray{ obj1, obj2 } ); | |
doc.setObject( obj ); | |
qDebug() << "\nAFTER:\n" | |
<< qPrintable( doc.toJson( QJsonDocument::Indented ) ); | |
// Add more objects to array | |
const auto obj3 = QJsonObject | |
{ | |
{ "name", "def" }, | |
{ "default", 33 }, | |
{ "new1", "1" }, | |
{ "new2", "2" } // Add any number of objects... | |
}; | |
const auto obj4 = QJsonObject{ { "name", "jkl" }, { "default", 44 } }; | |
// Get existing array to append more elements | |
auto arr = doc.object()[ "array" ].toArray(); | |
arr.append( obj3 ); | |
arr.append( obj4 ); | |
// Set old array to newly updated one | |
obj[ "array" ] = arr; | |
doc.setObject( obj ); | |
qDebug() << "\nAFTER THAT:\n" | |
<< qPrintable( doc.toJson( QJsonDocument::Indented ) ); | |
return 0; | |
} | |
/* | |
// OUTPUT: | |
BEFORE: | |
{ | |
"Name": "45", | |
"Path": "C:\file.json" | |
} | |
AFTER: | |
{ | |
"Name": "45", | |
"Path": "C:\file.json", | |
"array": [ | |
{ | |
"default": 11, | |
"name": "abc" | |
}, | |
{ | |
"default": 22, | |
"name": "xyz" | |
} | |
] | |
} | |
AFTER THAT: | |
{ | |
"Name": "45", | |
"Path": "C:\file.json", | |
"array": [ | |
{ | |
"default": 11, | |
"name": "abc" | |
}, | |
{ | |
"default": 22, | |
"name": "xyz" | |
}, | |
{ | |
"default": 33, | |
"name": "def", | |
"new1": "1", | |
"new2": "2" | |
}, | |
{ | |
"default": 44, | |
"name": "jkl" | |
} | |
] | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment