I have a json file as shown below
{
"TestId:1": {
"FILE ID": "223",
"CLASS": "rame",
"PLATFORM": "test"
},
"TestId:2": {
"FILE ID": "123",
"CLASS": "raj",
"PLATFORM": "test2"
}
}
I want to remove the "TestId:2" key content.
I tried delete obj["TestId:2"]; but that did not worked. It is deleting only the key "TestId:2"
I want to delete key with the value.
Can someone help me on this?
You need to create a QJsonObject to edit it.
First, read your file:
QFile file("myfile.json"); // to replace with you file name
file.open(QIODevice::ReadOnly);
QByteArray data = file.readAll();
file.close();
Then, create the QJsonDocument with the data from the file:
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(data, &error);
Then get the root object of the document:
QJsonObject root = doc.object();
Remove the element in the object, for exemple:
root.remove("TestId:2");
Then create a new document with the modified element:
doc = QJsonDocument(root);
And finally write the file again:
file.open(QIODevice::WriteOnly);
file.write(doc.toJson());
file.close();
And that should do the job.
As usual, there are many checks to add everywhere (file open, JSON parsing, etc).
Related
Q_PLUGIN_METADATA(IID "descComponentIID" FILE "file.json")
How to utilize the json file for configuring a component.
My Purpose is to store the configuration of a component like if
its a paint canvas component then storing the size of the canvas
or the background colour of the component?
//Suppose A JSON file is created
Example Test.json
{
"Name" : "Test",
"Version" : "1.0.1",
"CompatVersion" : "1.0.0",
"Vendor" : "My Company",
"Copyright" : "(C) 2016 MyCompany",
"License" : [
"This is a default license bla",
"blubbblubb",
"end of terms"
]
}
//Now Access metadata with the PluingLoader Which is used to load the
QJsonObject QPluginLoader::metaData() const
//The QJsonObject can be resursively traversed and QJsonValue can be
QJsonValue take(QLatin1String key)
I will post a small draft to help me provide an explanation.
nmplugin.json
{
"name": "nm",
"arguments": "--some-args"
}
You must access the "Metadata" key before any other entry in the json file. Don't forget to test the returned QJsonValue with isUndefined() to be on the safe side.
QJsonObject object{ loader->metaData().value("MetaData").toObject() };
qDebug() << object.value("name"); // Will print "nm"
I am trying to figure out how to extract data from Telegram which is JSON Data. I am using RapidJSON but when i tried the code below, i dont see any data extracted.
JSON
{
"ok":true,
"result":{
"message_id":90,
"from":{
"id":123456854,
"is_bot":true,
"first_name":"TestTGBot",
"username":"TestTGBot"
},
"chat":{
"id":125415667,
"first_name":"Test Account",
"type":"private"
},
"date":1506507292,
"text":"Test Bot Message"
}
}
Code
Document document;
document.Parse(rBuffer.c_str());
for(Value::ConstMemberIterator iter = document.MemberBegin();iter!=document.MemberEnd();++iter)
{
tmp.Format("%s",iter->name.GetString());
MessageBox(tmp);
}
It only returns "ok" and "result" value.
I am new in qt and I also searched in stack overflow but I can't get my answer so this not a duplicated post because all similar post have array [] but in this code i have not any array
I want to parse this complex JSON file:
{
"query": {
"lang": "en-US",
"results": {
"channel": {
"units": {
"distance": "mi",
"pressure": "in"
},
"ttl": "60",
"location": {
"city": "city",
"country": "not important",
"region": " kkk"
},
"wind": {
"chill": "99",
"direction": "180",
"speed": "14"
}
}
...(more code)
i want to get chill data but out put is " " , please help me to print chill data in qt
its a part of my code:
QNetworkAccessManager manager;
QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
QEventLoop event;
connect(response, SIGNAL(finished()), &event, SLOT(quit()));
event.exec();
json = response->readAll();
QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
QJsonObject jsonObj = doc.object();
foreach (const QJsonValue &value, jsonObj) {
QJsonObject jsonobj = value.toObject();
qDebug() << jsonobj["chill"].toString();
}
output of qDebug()<<doc.object(); is
D/libuntitled7.so(13258): : ** QJsonObject({"query":{"count":1,"created":"2017-07-06T21:21:16Z","lang":"en-US","results":{"channel":{"astronomy":{"sunrise":"5:48 am","sunset":"8:15 pm"},"atmosphere":{"humidity":"16","pressure":"875.0","rising":"0","visibility":"16.1"},"description":"Yahoo! Weather","image":{"height":"18","link":"http://weather.yahoo.com","title":"Yahoo! Weather","url":"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif","width":"142"},"item":{"condition":{"code":"31","date":"Fri, 07 Jul 2017 12:30 AM IRDT","temp":"85","text":"Clear"},"description":"<![CDATA[<img src=\"http://l.yimg.com/a/i/us/we/52/31.gif\"/>\n<BR/>\n<b>Forecast:</b>\n<BR /> Fri - Sunny. High: 97Low: 78\n<BR /> Sat - Sunny. High: 100Low: 79\n<BR /> Sun - Sunny. High: 101Low: 81\n<BR /> Mon - Sunny. High: 100Low: 81\n<BR /> Tue - Mostly
D/libuntitled7.so(13258): ..\untitled7\dialog2.cpp:84 (void Dialog2::on_pushButton_clicked()):
and next out put is 86
As I comment #MohammedB.B. a way is to manually search through the keys, another way is to create a function that searches through the keys, in this case I present the second form:
QJsonObject findObject(QString key, QJsonObject object){
if(object.isEmpty())
return QJsonObject();
if(object.keys().contains(key)){
return object;
}
else{
for(const QString& _key: object.keys()){
if(object[_key].isObject()){
const QJsonObject& result = findObject(key, object[_key].toObject());
if(!result.isEmpty()){
return result;
}
}
}
}
return QJsonObject();
}
QJsonValue findValuebyKey(QString key, QJsonDocument doc){
QJsonObject obj_key = findObject(key, doc.object());
return obj_key[key];
}
Example:
QJsonDocument doc = QJsonDocument::fromJson(json.toUtf8());
qDebug()<<findValuebyKey("chill", doc).toString();
Output:
"99"
Note:If you generate problems the "for" enable c ++ 11, you can do this by adding CONFIG += c++11 to your .pro
You need to iterate in your channels array too. Easy solution:
const QJsonDocument doc = QJsonDocument::fromJson(response->readAll().toUtf8());
// Access to "query"
const QJsonObject queryObject = doc.object();
// Access to "results"
const QJsonObject resultsObject = queryObject.value("results").toObject();
// Access to "chanels"
const QJsonObject channelsObject = resultsObject.value("channels").toObject();
// Access to "wind"
const QJsonObject windObject = channelsObject.value("wind").toObject();
// And then access to "chill"
const QJsonValue chill = windObject.value("chill");
Best practice its to create a recursive function to parse the JSON recursively.
I have been trying all day to read data from a json file like below with Qt but can't find a way to do it properly. I tried many things but could not get it right. Can someone help me how to get this correctly?
{
"RawData": {
"Sensors": {
"Channel1" : "10",
"Channel2" : "22",
"Channel3" : "3",
"Channel4" : "48",
"Channel5" : "1",
"Channel6" : "8",
"Channel7" : "16",
"Channel8" : "44"
}
}
}
for now my code looks something like this, though i tried many things with different manners.
QFile jsonCfg("config.json");
if (!jsonCfg.open(QIODevice::ReadOnly)) {
qWarning("Couldn't open json config file.");
return false;
}
QByteArray saveData = jsonCfg.readAll();
QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
QJsonObject config = loadDoc.object();
QVariantMap root_map = config.toVariantMap();
QVariantMap raw = root_map["RawData"].toMap();
QVariantMap sensor = raw["Sensors"].toMap();
qDebug() << "channel 1" << sensor["Channel1"].toDouble();
you can use QJsonDocument and QJsonObject just like:
QJsonParseError jsonErr;
QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr,&jsonErr);
if(jsonErr.error == QJsonParseError::NoError)
{
QJsonObject myJsonObject = jsonDoc.object();
if(myJsonObject["RawData"].isObject())
{
//do somethine your want;
}
}
i want to decode following json with qt:
{
"user": {
"name": "string"
}
}
i'm tried to do it with this code, but does not work:
QJsonDocument jsonResponse = QJsonDocument::fromJson(result.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonArray jsonArray = jsonObject["user"].toArray();
foreach (const QJsonValue & value, jsonArray)
{
QJsonObject obj = value.toObject();
url = obj["name"].toString();
}
This is the culprit:
QJsonArray jsonArray = jsonObject["user"].toArray();
You are trying to convert the object to an array without any isArray() check. That is, your json does not contain an array therein. Array means [...] in the json world.
You ought to either use toObject() or change your input json.
Without json file change, you would write this:
QJsonDocument jsonResponse = QJsonDocument::fromJson(result.toUtf8());
QJsonObject jsonObject = jsonResponse.object();
QJsonObject userJsonObject = jsonObject.value("user").toObject();
qDebug() << userJsonObject.value("name").toString();