JSON array with multiple values c++ -
i have body request example:
{ "users": [{ "userid": 123 }, { "userid": 1234 }] }
for previous example receive 1 std::list<usersid>* vusers
have userid (in case '123' , '1234'), create cjson array
, iterate list , userid. (note: usersid
1 auxiliar class use , receive 1 int
in constructor)
cjson* cjsonusers = cjson_createarray(); cjson_additemtoobject(root, "vusers", cjsonusers); std::list<usersid>::const_iterator itusers = vusers->begin(); while (itusers != vusers->end()) { cjson *cjsonvnode = cjson_createobject(); cjson_additemtoarray(cjsonusers, cjsonuser); cjson_addnumbertoobject(cjsonuser, "userid", itusers->userid); ++itvnodes; }
but know want same make more simple/easy , need change body request this:
{ "users": { "userid": [123, 1234] } }
i'm using c++ library -> https://github.com/davegamble/cjson dont understand how implement modification need.
edit 2 (parse json)
cjson* cjsonusers = cjson_getobjectitem(root, "users"); if (!cjsonusers) return 0; if (cjsonusers->type != cjson_array) return 0; std::list<vuserid>* users = new std::list<vuserid>(); cjson* cjsonvuser; cjson_arrayforeach(cjsonvuser, cjsonusers) { cjson* cjsonvuserid = cjson_getobjectitem(cjsonvuser, "userid"); if (!cjsonvuserid) continue; int user_id = cjsonvuserid->valueint; vuserid userid(user_id); users->push_back(userid); }
something work, is, create object , array outside of loop, , insert numbers inside loop:
cjson* cjsonusers = cjson_createobject(); cjson_additemtoobject(root, "users", cjsonusers); cjson* cjsonuserid = cjson_createarray(); cjson_additemtoobject(cjsonusers, "userid", cjsonuserid); std::list<usersid>::const_iterator itusers = vusers->begin(); while (itusers != vusers->end()) { cjson_additemtoarray(cjsonuserid, cjson_createnumber(itusers->userid)); ++itvnodes; }
note there languages out there more convenient manipulate json if have flexibility (disclaimer: involved in design of of these). of course there use cases when have use c++ , in library makes lot of sense.
with languages such c++ or java, there impedance mismatch between objects in classical sense, , data formats xml or json. example, standardized, declarative , functional xquery 3.1 not need code transform first document second:
let $original-document := json-doc("users.json") return map { "users" : map { "userid" : array { $original-document?users?*?userid } } }
Comments
Post a Comment