gpt4 book ai didi

c++ - 添加文本到json C++

转载 作者:太空宇宙 更新时间:2023-11-04 15:56:50 24 4
gpt4 key购买 nike

有一个JSON文件,我怎样才能在那里添加信息以便留下过去?做了这样的事情,不起作用:

QFile File(pathJSONProject);
File.open(QIODevice::ReadOnly | QIODevice::Text);
QJsonParseError JsonParseError;
QJsonDocument JsonDocument = QJsonDocument::fromJson(File.readAll(), &JsonParseError);

QJsonObject json = JsonDocument.object();

json.insert("Расстояние", dlgOpen->distance);
json.insert("Размер", dlgOpen->size);
json.insert("Путь", pathFolder);
QJsonDocument document(json);
File.open(QFile::WriteOnly | QFile::Text | QFile::Truncate);
File.write(document.toJson());
File.close();

我想向文件中添加条目。做不到。它不会改变。

首先,文件是这样的吗?他必须如何添加新条目?

{
"Name": "45",
"Path": "C:/Users/Dmitry/Desktop/45.json"
}

如何向数组添加新条目?

enter image description here

最佳答案

始终处理QFile::open() 的返回值以检查它是否成功。


可以有多种方式在 JSON 中插入数组。这是一个例子:

#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;
}

输出:

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"
}
]
}

另外,看看 QJsonArray::fromStringList()QJsonArray::fromVariantList() .

关于c++ - 添加文本到json C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55296139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com