Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON array using casablanca

I am trying to read from a JSON response in Casablanca. The sent data looks like this:

{
"devices":[
  {"id":"id1",
   "type":"type1"},
  {"id":"id2",
   "type":"type2"}
]
}

Does anyone know how to do this? Casablanca tutorials only seem to care about creating such arrays and not about reading from them.

like image 364
spiralstatic Avatar asked Nov 30 '22 10:11

spiralstatic


1 Answers

Let's assume you got your json as an http response:

web::json::value json;
web::http::http_request request;

//fill the request properly, then send it:

client
.request(request)
.then([&json](web::http::http_response response)
{
    json = response.extract_json().get();
})
.wait();

Note that no error checking is done here, so let's assume everything works fine (--if not,see the Casablanca documentation and examples).

The returned json can then be read via the at(utility::string_t) function. In your case it is an array (you either know that or check it via is_array()):

auto array = json.at(U("devices")).as_array();
for(int i=0; i<array.size(); ++i)
{
     auto id = array[i].at(U("id")).as_string();
     auto type = array[i].at(U("type")).as_string();
}

With this you get the entries of the json response stored in string variables.

In reality, you further might want to check whether the response has the coresponding fields, e.g. via has_field(U("id")), and if so, check whether the entries are not null via is_null() -- otherwise, the as_string() function throws an exception.

like image 157
davidhigh Avatar answered Dec 11 '22 23:12

davidhigh