JSON с использованием nlohmann :: json jpointer для динамического c строки и значения по умолчанию - PullRequest
0 голосов
/ 05 мая 2020

В библиотеке nlohmann :: json, если ключ не найден, предусмотрена возможность возврата такого значения по умолчанию, как это

j.value("/Parent/child"_json_pointer, 100);

здесь 100 будет возвращено, если "/ Parent / child" равно не найдено Но если "/ Parent / child" - это динамический c как массив, например

например. / Parent / child / array / 0 / key
/ Parent / child / array / 1 / key
, тогда мне нужно создать json указатель, как показано ниже

nlohmann::json::json_pointer jptr(str) //str = "/Parent/child/array/0/key"

Как получить поведение значения по умолчанию с "jptr". Есть ли другой подход.

Добавление образца кода.

Json Файл

{
        "GNBDUFunction": {
                "gnbLoggingConfig": [{
                                "moduleId": "OAMAG",
                                "logLevel": "TRC"
                        },
                        {
                                "moduleId": "FSPKT",
                                "logLevel": "TRC"
                        }
                ],
                "ngpLoggingConfig": [{
                                "moduleId": "MEM",
                                "logLevel": "FATAL"
                        },
                        {
                                "moduleId": "BUF",
                                "logLevel": "FATAL"
                        },
                        {
                                "moduleId": "PERF",
                                "logLevel": "FATAL"
                        }
                ]
        }
}

Код

#include <iostream>
#include <fstream>
#include <nlohmann/json.hpp>
#include <string>
using namespace std;
using json = nlohmann::json;

void parse(json& j,std::string path) {

nlohmann::json::json_pointer jptr(path);
json &child = j.at(jptr);
std::string moduleId = child.at("moduleId");
std::string loglvl = child.at("logLevel","FATAL");//How to get with default ??
}

int main()
{
 std::ifstream name("test.json");
 json j = nlohmann::json::parse(name);
 std::string path ="GNBDUFunction/gnbLoggingConfig";
 int count  = j.at("/GNBDUFunction/gnbLoggingConfig"_json_pointer).size();
 for (int i = 0 ; i < count ;++i)
 {
     const std::string sub_path = "/" + path + "/" +std::to_string(i);
     parse(j,sub_path);
 }

return 0;
}

1 Ответ

0 голосов
/ 05 мая 2020

Прежде всего, вы можете просто использовать ::value с json_pointer. Во-вторых, вы можете использовать оператор / для создания новых json_pointers. Таким образом, ваша функция main может делать следующее:

json j = nlohmann::json::parse(name);
auto root = "/GNBDUFunction/gnbLoggingConfig"_json_pointer;
size_t count  = j.at(root).size();
for (size_t i = 0 ; i < count ; ++i) {
    auto sub_path = root / i / "moduleId" / "logLevel";
    std::string loglvl = j.value(sub_path, "FATAL");
}

...