Protective Stop
Loading...
Searching...
No Matches
json_lite.hpp
1// SPDX-FileCopyrightText: 2026 Polymath Robotics, Inc.
2// SPDX-License-Identifier: Apache-2.0
3#pragma once
4
5#include <cctype>
6#include <cstdlib>
7#include <map>
8#include <string>
9#include <utility>
10#include <vector>
11
12namespace jsonlite
13{
14
17struct Value
18{
20 enum Type
21 {
22 NUL,
23 BOOL,
24 NUM,
25 STR,
26 ARR,
27 OBJ
28 };
29
31 Type type{NUL};
33 bool b{false};
35 double num{0.0};
37 std::string str;
39 std::vector<Value> arr;
41 std::map<std::string, Value> obj;
42
44 bool is_obj() const
45 {
46 return type == OBJ;
47 }
48
50 bool is_arr() const
51 {
52 return type == ARR;
53 }
54
56 const Value * find(const std::string & key) const
57 {
58 if (type != OBJ) {
59 return nullptr;
60 }
61 auto it = obj.find(key);
62 return it == obj.end() ? nullptr : &it->second;
63 }
64
66 double as_num(double dflt = 0.0) const
67 {
68 return type == NUM ? num : dflt;
69 }
70
72 bool as_bool(bool dflt = false) const
73 {
74 if (type == BOOL) {
75 return b;
76 }
77 if (type == NUM) {
78 return num != 0.0;
79 }
80 return dflt;
81 }
82
84 std::string as_str(const std::string & dflt = "") const
85 {
86 return type == STR ? str : dflt;
87 }
88
90 double num_at(const std::string & k, double dflt = 0.0) const
91 {
92 const Value * v = find(k);
93 return v ? v->as_num(dflt) : dflt;
94 }
95
97 bool bool_at(const std::string & k, bool dflt = false) const
98 {
99 const Value * v = find(k);
100 return v ? v->as_bool(dflt) : dflt;
101 }
102
104 std::string str_at(const std::string & k, const std::string & dflt = "") const
105 {
106 const Value * v = find(k);
107 return v ? v->as_str(dflt) : dflt;
108 }
109};
110
114{
115public:
117 explicit Parser(const std::string & s)
118 : s_(s)
119 {}
120
124 bool parse(Value & out)
125 {
126 skip_ws();
127 if (!value(out, 0)) {
128 return false;
129 }
130 skip_ws();
131 // trailing junk tolerated
132 return true;
133 }
134
135private:
136 const std::string & s_;
137 size_t i_{0};
138 // Bound recursion so a hostile/malformed deeply-nested document (e.g. from a
139 // compromised device) can't overflow the stack. The device schema is flat.
140 static constexpr int kMaxDepth = 32;
141
142 void skip_ws()
143 {
144 while (i_ < s_.size() && std::isspace(static_cast<unsigned char>(s_[i_]))) {
145 ++i_;
146 }
147 }
148
149 char peek() const
150 {
151 return i_ < s_.size() ? s_[i_] : '\0';
152 }
153
154 bool value(Value & v, int depth)
155 {
156 if (depth > kMaxDepth) {
157 return false;
158 }
159 skip_ws();
160 char c = peek();
161 switch (c) {
162 case '{':
163 return object(v, depth);
164 case '[':
165 return array(v, depth);
166 case '"':
167 return string_val(v);
168 case 't':
169 case 'f':
170 return boolean(v);
171 case 'n':
172 return null_val(v);
173 default:
174 if (c == '-' || std::isdigit(static_cast<unsigned char>(c))) {
175 return number(v);
176 }
177 return false;
178 }
179 }
180
181 bool object(Value & v, int depth)
182 {
183 v.type = Value::OBJ;
184 // consume {
185 ++i_;
186 skip_ws();
187 if (peek() == '}') {
188 ++i_;
189 return true;
190 }
191 while (true) {
192 skip_ws();
193 if (peek() != '"') {
194 return false;
195 }
196 Value key;
197 if (!string_val(key)) {
198 return false;
199 }
200 skip_ws();
201 if (peek() != ':') {
202 return false;
203 }
204 ++i_;
205 Value val;
206 if (!value(val, depth + 1)) {
207 return false;
208 }
209 v.obj[key.str] = std::move(val);
210 skip_ws();
211 char c = peek();
212 if (c == ',') {
213 ++i_;
214 continue;
215 }
216 if (c == '}') {
217 ++i_;
218 return true;
219 }
220 return false;
221 }
222 }
223
224 bool array(Value & v, int depth)
225 {
226 v.type = Value::ARR;
227 // consume [
228 ++i_;
229 skip_ws();
230 if (peek() == ']') {
231 ++i_;
232 return true;
233 }
234 while (true) {
235 Value item;
236 if (!value(item, depth + 1)) {
237 return false;
238 }
239 v.arr.push_back(std::move(item));
240 skip_ws();
241 char c = peek();
242 if (c == ',') {
243 ++i_;
244 continue;
245 }
246 if (c == ']') {
247 ++i_;
248 return true;
249 }
250 return false;
251 }
252 }
253
254 bool string_val(Value & v)
255 {
256 v.type = Value::STR;
257 // consume the opening quote
258 ++i_;
259 std::string out;
260 while (i_ < s_.size()) {
261 char c = s_[i_++];
262 if (c == '"') {
263 v.str = std::move(out);
264 return true;
265 }
266 if (c == '\\' && i_ < s_.size()) {
267 char e = s_[i_++];
268 switch (e) {
269 case 'n':
270 out.push_back('\n');
271 break;
272 case 't':
273 out.push_back('\t');
274 break;
275 case 'r':
276 out.push_back('\r');
277 break;
278 case '"':
279 out.push_back('"');
280 break;
281 case '\\':
282 out.push_back('\\');
283 break;
284 case '/':
285 out.push_back('/');
286 break;
287 // passthrough: keep the 4 hex digits literally
288 case 'u':
289 out.push_back('\\');
290 out.push_back('u');
291 for (int k = 0; k < 4 && i_ < s_.size(); ++k) {
292 out.push_back(s_[i_++]);
293 }
294 break;
295 default:
296 out.push_back(e);
297 break;
298 }
299 } else {
300 out.push_back(c);
301 }
302 }
303 // unterminated
304 return false;
305 }
306
307 bool number(Value & v)
308 {
309 size_t start = i_;
310 if (peek() == '-') {
311 ++i_;
312 }
313 while (i_ < s_.size() && (std::isdigit(static_cast<unsigned char>(s_[i_])) || s_[i_] == '.' || s_[i_] == 'e' ||
314 s_[i_] == 'E' || s_[i_] == '+' || s_[i_] == '-'))
315 {
316 ++i_;
317 }
318 v.type = Value::NUM;
319 v.num = std::strtod(s_.substr(start, i_ - start).c_str(), nullptr);
320 return true;
321 }
322
323 bool boolean(Value & v)
324 {
325 if (s_.compare(i_, 4, "true") == 0) {
326 v.type = Value::BOOL;
327 v.b = true;
328 i_ += 4;
329 return true;
330 }
331 if (s_.compare(i_, 5, "false") == 0) {
332 v.type = Value::BOOL;
333 v.b = false;
334 i_ += 5;
335 return true;
336 }
337 return false;
338 }
339
340 bool null_val(Value & v)
341 {
342 if (s_.compare(i_, 4, "null") == 0) {
343 v.type = Value::NUL;
344 i_ += 4;
345 return true;
346 }
347 return false;
348 }
349};
350
351inline bool parse(const std::string & text, Value & out)
352{
353 Parser p(text);
354 return p.parse(out);
355}
356
357} // namespace jsonlite
Recursive-descent parser for the flat JSON schema of the ESP32 /state.json.
Definition json_lite.hpp:114
Parser(const std::string &s)
Parses s; the string must outlive the parser.
Definition json_lite.hpp:117
bool parse(Value &out)
Parses the document into out.
Definition json_lite.hpp:124
A parsed JSON value: null, bool, number, string, array or object.
Definition json_lite.hpp:18
bool as_bool(bool dflt=false) const
Bool value, a NUM compared against zero, or dflt for other types.
Definition json_lite.hpp:72
double num
Value when type is NUM.
Definition json_lite.hpp:35
std::vector< Value > arr
Elements when type is ARR.
Definition json_lite.hpp:39
bool bool_at(const std::string &k, bool dflt=false) const
as_bool() of member k, or dflt if the member is absent.
Definition json_lite.hpp:97
double as_num(double dflt=0.0) const
Number value, or dflt unless type is NUM.
Definition json_lite.hpp:66
std::string as_str(const std::string &dflt="") const
String value, or dflt unless type is STR.
Definition json_lite.hpp:84
bool b
Value when type is BOOL.
Definition json_lite.hpp:33
Type type
Active type; selects which of the members below is meaningful.
Definition json_lite.hpp:31
bool is_arr() const
True when type is ARR.
Definition json_lite.hpp:50
bool is_obj() const
True when type is OBJ.
Definition json_lite.hpp:44
double num_at(const std::string &k, double dflt=0.0) const
as_num() of member k, or dflt if the member is absent.
Definition json_lite.hpp:90
Type
JSON type held by a Value.
Definition json_lite.hpp:21
std::map< std::string, Value > obj
Members when type is OBJ.
Definition json_lite.hpp:41
std::string str_at(const std::string &k, const std::string &dflt="") const
as_str() of member k, or dflt if the member is absent.
Definition json_lite.hpp:104
std::string str
Value when type is STR.
Definition json_lite.hpp:37
const Value * find(const std::string &key) const
Returns the member named key, or nullptr if absent or not an object.
Definition json_lite.hpp:56