我需要使用 jsoncpp 庫在 json 檔案中搜索元素。我無法理解如何到達最內部的陣列......有什么想法嗎?
{
"key": int,
"array1": [
{
"key": int,
"array2": [
{
"key": int,
"array3": [
{
"needed_key": int
}
]
}
]
}
]
}
到目前為止,我嘗試過這樣的事情:
const Json::Value& array1 = root["array1"];
for (size_t i = 0; i < array1.size(); i )
{
const Json::Value& array2 = array1["array2"];
for (size_t j = 0; j < array2.size(); j )
{
const Json::Value& array3 = array2["array3"];
for (size_t k = 0; k < array3.size(); k )
{
std::cout << "Needed Key: " << array3["needed_key"].asInt();
}
}
}
但它拋出:
JSONCPP_NORETURN void throwLogicError(String const& msg) {
throw LogicError(msg);
}
uj5u.com熱心網友回復:
您無法訪問array2with array1["array2"],因為array1它包含一個物件陣列,而不是一個物件,因此您應該array2使用 index來獲取。iarray1[i]["array2"]
以下代碼適用于我:
const Json::Value &array1 = root["array1"];
for (int i = 0; i < array1.size(); i ) {
const Json::Value &array2 = array1[i]["array2"];
for (int j = 0; j < array2.size(); j ) {
const Json::Value &array3 = array2[j]["array3"];
for (int k = 0; k < array3.size(); k ) {
std::cout << "Needed Key: " << array3[k]["needed_key"].asInt();
}
}
}
輸出如下所示:
Needed Key: 4
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465324.html
上一篇:使用JOLT將字典轉換為物件
