gpt4 book ai didi

c++ - 使用 nlohmann json 进行 JSON 解析

转载 作者:行者123 更新时间:2023-11-27 23:48:15 26 4
gpt4 key购买 nike

我正在尝试使用 nlohmann 的 json.hpp 解析 JSON 结构.但我不会从字符串创建 JSON 结构。我已经尝试了所有方法,但仍然失败。

我的要求是:

1) 从字符串创建 JSON 结构。

2) 从中找出"statusCode"的值。

试了这么久,我真的有点疑惑了,nlohmann的json解析器是否支持嵌套的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": {

最佳答案

因为 " 是开始和结束字符串文字的字符,所以如果不放置 \ 就不能在字符串中包含 " 字符在此之前。

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

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

当你想制作包含很多 " 的字符串时,一个更简单的选择是使用 R"" string literal 。然后你可以这样写所以。

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

关于c++ - 使用 nlohmann json 进行 JSON 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48825709/

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