Intial somewhat working version
This commit is contained in:
48
src/JsonUtil.cpp
Normal file
48
src/JsonUtil.cpp
Normal file
@@ -0,0 +1,48 @@
|
||||
#include "JsonUtil.h"
|
||||
|
||||
#include <charconv>
|
||||
|
||||
std::string jsonEscape(const std::string& value)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(value.size());
|
||||
for (char ch : value)
|
||||
{
|
||||
switch (ch)
|
||||
{
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '"': out += "\\\""; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
default: out += ch; break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::optional<float> findJsonFloat(const std::string& body, const std::string& key)
|
||||
{
|
||||
const std::string quotedKey = "\"" + key + "\"";
|
||||
size_t pos = body.find(quotedKey);
|
||||
if (pos == std::string::npos)
|
||||
return std::nullopt;
|
||||
|
||||
pos = body.find(':', pos + quotedKey.size());
|
||||
if (pos == std::string::npos)
|
||||
return std::nullopt;
|
||||
++pos;
|
||||
|
||||
while (pos < body.size() && (body[pos] == ' ' || body[pos] == '\t' || body[pos] == '\r' || body[pos] == '\n'))
|
||||
++pos;
|
||||
|
||||
size_t end = pos;
|
||||
while (end < body.size() && (body[end] == '-' || body[end] == '+' || body[end] == '.' || (body[end] >= '0' && body[end] <= '9') || body[end] == 'e' || body[end] == 'E'))
|
||||
++end;
|
||||
|
||||
float value = 0.0f;
|
||||
const auto result = std::from_chars(body.data() + pos, body.data() + end, value);
|
||||
if (result.ec != std::errc())
|
||||
return std::nullopt;
|
||||
return value;
|
||||
}
|
||||
Reference in New Issue
Block a user