Разбор JSON с использованием nlohmann json

Я пытаюсь проанализировать структуру JSON с помощью nlohmann's json.hpp . Но я не должен создавать структуру JSON из строки. Я пытался все время, но все равно не получается.

Мое требование:

1) Создайте структуру JSON из строки.

2) Найти значение "statusCode" из него.

После стольких попыток я действительно сомневаюсь, поддерживает ли json-парсер nlohmann вложенный JSON или нет.

#include "json.hpp"
using namespace std;

int main(){

    // giving error 1
    nlohmann::json strjson = nlohmann::json::parse({"statusResp":{"statusCode":"S001","message":"Registration Success","snStatus":"Active","warrantyStart":"00000000","warrantyEnd":"00000000","companyBPID":"0002210887","siteBPID":"0002210888","contractStart":"00000000","contractEnd":"00000000"}});

    // Giving error 2:
   auto j= "{
    "statusResp": {
        "statusCode": "S001",
        "message": "Registration Success",
        "snStatus": "Active",
        "warrantyStart": "20170601",
        "warrantyEnd": "20270601",
        "companyBPID": "0002210887",
        "siteBPID": "0002210888",
        "contractStart": "00000000",
        "contractEnd": "00000000"
    }
   }"_json;

   // I actually want to get the value of "statusCode" code from the JSOn structure. But no idea how to parse the nested value.
    return 1;

}

Ниже приведены ошибки для обеих инициализаций:

//ERROR 1:
test.cpp: In function 'int main()':
test.cpp:17:65: error: expected '}' before ':' token
     nlohmann::json strjson = nlohmann::json::parse({"statusResp":{"statusCode":"S001","message":"Registration Success","snStatus":"Active","warrantyStart":"00000000","warrantyEnd":"00000000","companyBPID":"0002210887","siteBPID":"0002210888","contractStart":"00000000","contractEnd":"00000000"}});

// ERROR 2:
hemanty@sLinux:/u/hemanty/workspaces/avac/cb-product/mgmt/framework/src/lib/libcurl_cpp$g++ test.cpp -std=gnu++11
test.cpp: In function 'int main()':
test.cpp:27:17: error: expected '}' before ':' token
     "statusResp": {

2 ответа

Поскольку " символ начала и конца строкового литерала, который вы не можете иметь " символ внутри строки, не помещая \ перед этим.

std::string str = " "statusCode":"5001" "; //This does not work

std::string str = " \"statusCode\":\"5001\" "; //This will work

Более простая альтернатива, когда вы хотите сделать строки с большим количеством " в них стоит использовать R"" строковый литерал. Тогда вы можете написать это так.

std::string str = R"("statusCode":"5001")";

Если мы теперь перенесем это на ваш пример json, правильный способ анализа строк будет одним из следующих.

auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }");
// and below the equivalent with raw string literal
auto j3 = json::parse(R"({"happy": true, "pi": 3.141 })");

//Here we use the `_json` suffix 
auto j2 = "
{
    \"happy\": true,
    \"pi\": 3.141
}"_json;
// Here we combine the R"" with _json suffix to do the same thing.
auto j2 = R"(
{
    "happy": true,
    "pi": 3.141
  }
)"_json;

Примеры взяты из readme

Если это то, что вам нужно:

      std::string ss= R"(
{
    "test-data":
    [
        {
            "name": "tom",
            "age": 11
        },
        {
            "name": "jane",
            "age": 12
        }
    ]
}
)";

json myjson = json::parse(ss);
auto &students = myjson["test-data"];

for(auto &student : students) {
    cout << "name=" << student["name"].get<std::string>() << endl;
}

Или же:

      json myjson = { {"name", "tom"}, {"age", 11} };
cout << "name=" << myjson["name"].get<std::string>() << endl;
Другие вопросы по тегам