| 317 | * false, ss is valid */ |
| 318 | |
| 319 | bool |
| 320 | cmdmap_from_json(const vector<string>& cmd, cmdmap_t *mapp, std::ostream& ss) |
| 321 | { |
| 322 | json_spirit::mValue v; |
| 323 | |
| 324 | string fullcmd; |
| 325 | // First, join all cmd strings |
| 326 | for (auto& c : cmd) |
| 327 | fullcmd += c; |
| 328 | |
| 329 | try { |
| 330 | if (!json_spirit::read(fullcmd, v)) |
| 331 | throw std::runtime_error("unparseable JSON " + fullcmd); |
| 332 | if (v.type() != json_spirit::obj_type) |
| 333 | throw std::runtime_error("not JSON object " + fullcmd); |
| 334 | |
| 335 | // allocate new mObject (map) to return |
| 336 | // make sure all contents are simple types (not arrays or objects) |
| 337 | json_spirit::mObject o = v.get_obj(); |
| 338 | for (auto it = o.begin(); it != o.end(); ++it) { |
| 339 | |
| 340 | // ok, marshal it into our string->cmd_vartype map, or throw an |
| 341 | // exception if it's not a simple datatype. This is kind of |
| 342 | // annoying, since json_spirit has a boost::variant inside it |
| 343 | // already, but it's not public. Oh well. |
| 344 | |
| 345 | switch (it->second.type()) { |
| 346 | |
| 347 | case json_spirit::obj_type: |
| 348 | default: |
| 349 | throw std::runtime_error("JSON array/object not allowed " + fullcmd); |
| 350 | break; |
| 351 | |
| 352 | case json_spirit::array_type: |
| 353 | { |
| 354 | // array is a vector of values. Unpack it to a vector |
| 355 | // of strings, doubles, or int64_t, the only types we handle. |
| 356 | const vector<json_spirit::mValue>& spvals = it->second.get_array(); |
| 357 | if (spvals.empty()) { |
| 358 | // if an empty array is acceptable, the caller should always check for |
| 359 | // vector<string> if the expected value of "vector<int64_t>" in the |
| 360 | // cmdmap is missing. |
| 361 | (*mapp)[it->first] = vector<string>(); |
| 362 | } else if (spvals.front().type() == json_spirit::str_type) { |
| 363 | vector<string> outv; |
| 364 | for (const auto& sv : spvals) { |
| 365 | if (sv.type() != json_spirit::str_type) { |
| 366 | throw std::runtime_error("Can't handle arrays of multiple types"); |
| 367 | } |
| 368 | outv.push_back(sv.get_str()); |
| 369 | } |
| 370 | (*mapp)[it->first] = std::move(outv); |
| 371 | } else if (spvals.front().type() == json_spirit::int_type) { |
| 372 | vector<int64_t> outv; |
| 373 | for (const auto& sv : spvals) { |
| 374 | if (spvals.front().type() != json_spirit::int_type) { |
| 375 | throw std::runtime_error("Can't handle arrays of multiple types"); |
| 376 | } |
no test coverage detected