gpt4 book ai didi

c++ - 在 C++ 中将不断变化的 json 值转换为 int

转载 作者:行者123 更新时间:2023-11-28 04:17:30 24 4
gpt4 key购买 nike

好的,我从我的客户那里得到了这个 JSON 对象:

{"command":"BrugerIndtastTF","brugerT":"\"10\"","brugerF":"\"20\""}

然后我需要使用来自“brugerT”的 int 值,但如您所见,它周围有“\”10\“”。当我用 javascript 编写代码时,我没有遇到这个问题。有没有办法只使用“brugerT”中表示 10 的部分?

*temp 只应打印 int 值 10 的代码:

socket_->hub_.onMessage([this](
uWS::WebSocket<uWS::SERVER> *ws,
char* message,
size_t length,
uWS::OpCode opCode
)
{

std::string data = std::string(message,length);
std::cout << "web::Server:\t Data received: " << data << std::endl;

// handle manual settings

std::cout << "Web::Server:\t Received request: manual. Redirecting message." << std::endl;

json test1 = json::parse(data);
auto test2 = test1.json::find("command");

std::cout << "Web::Server:\t Test 1" << test1 << std::endl;

std::cout << "Web::Server:\t Test 2" << *test2 << std::endl;

if (*test2 =="BrugerIndtastTF")
{
std::cout<<"Web::Server:\t BrugerIndtastTF modtaget" << std::endl;
auto temp= test1.json::find("brugerT");
auto humi= test1.json::find("brugerF");



std::cout << "Web::Server:\t temp: " << *temp << "humi: " << *humi << std::endl;
}



});

编辑: Here you can see the terminal

它应该只是说:temp: 10 humi: 20

最佳答案

你可以尝试获取brugerTstring值,将字符串中的\"去掉,然后转换成 >string 转换为带有 stoiint。您甚至可以使用正则表达式来查找 string 中的整数,并让该库找出是什么最佳匹配方法。正则表达式类似于:([0-9]+)

ps 字符串 literal type 6手动过滤掉 \"

时可能会有一些用处
#include <iostream>
#include <regex>
#include <string>
using namespace std;

int main() {
string inputStr(R"("\"10\"")");

regex matchStr(R"(([0-9]+))");
auto matchesBegin = sregex_iterator(inputStr.begin(), inputStr.end(), matchStr);
auto matchesEnd = sregex_iterator();

for (sregex_iterator i = matchesBegin; i != matchesEnd; ++i) {
cout << i->str() << endl;
}
return 0;
}

关于c++ - 在 C++ 中将不断变化的 json 值转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56288052/

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