upload
This commit is contained in:
65
libs/vslam_common/src/json_parse.cc
Normal file
65
libs/vslam_common/src/json_parse.cc
Normal file
@@ -0,0 +1,65 @@
|
||||
#include "vslam/json_parse.h"
|
||||
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace vslam {
|
||||
namespace {
|
||||
|
||||
// Tra ve vi tri ngay sau dau ':' cua "key", hoac npos.
|
||||
size_t FindValue(const std::string& body, const std::string& key) {
|
||||
const std::string pat = "\"" + key + "\"";
|
||||
size_t p = body.find(pat);
|
||||
if (p == std::string::npos) return std::string::npos;
|
||||
p += pat.size();
|
||||
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
|
||||
if (p >= body.size() || body[p] != ':') return std::string::npos;
|
||||
++p;
|
||||
while (p < body.size() && std::isspace(static_cast<unsigned char>(body[p]))) ++p;
|
||||
return p < body.size() ? p : std::string::npos;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool JsonGetNumber(const std::string& body, const std::string& key, double* out) {
|
||||
const size_t p = FindValue(body, key);
|
||||
if (p == std::string::npos) return false;
|
||||
|
||||
char* end = nullptr;
|
||||
const double v = std::strtod(body.c_str() + p, &end);
|
||||
if (end == body.c_str() + p) return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool JsonGetBool(const std::string& body, const std::string& key, bool* out) {
|
||||
const size_t p = FindValue(body, key);
|
||||
if (p == std::string::npos) return false;
|
||||
if (body.compare(p, 4, "true") == 0) { *out = true; return true; }
|
||||
if (body.compare(p, 5, "false") == 0) { *out = false; return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
bool JsonGetString(const std::string& body, const std::string& key, std::string* out) {
|
||||
const size_t p = FindValue(body, key);
|
||||
if (p == std::string::npos || body[p] != '"') return false;
|
||||
|
||||
out->clear();
|
||||
for (size_t i = p + 1; i < body.size(); ++i) {
|
||||
if (body[i] == '\\' && i + 1 < body.size()) {
|
||||
++i;
|
||||
switch (body[i]) {
|
||||
case 'n': out->push_back('\n'); break;
|
||||
case 't': out->push_back('\t'); break;
|
||||
case 'r': out->push_back('\r'); break;
|
||||
default: out->push_back(body[i]); break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (body[i] == '"') return true;
|
||||
out->push_back(body[i]);
|
||||
}
|
||||
return false; // chuoi khong dong
|
||||
}
|
||||
|
||||
} // namespace vslam
|
||||
Reference in New Issue
Block a user