问题
I have this code:
wcout << jvalue.serialize() << endl;
which prints out the whole body of json data:
{
"data": {
"timestamp": [
{
"_id": "5ad93fc48084e1089cd9667b",
"staff_id": 172,
"staff_name": "Michael Edano",
"time_in": "2018-04-20T01:17:56.787Z",
"time_out": null,
"status": ['Leave','Vacation','Absent'],
"createdAt": "2018-04-20T01:17:56.790Z",
"updatedAt": "2018-04-20T01:17:56.790Z",
"__v": 0
}
],
"success": true
}
}
Can someone give me an example on how to get let say the
_id
field
and
single data of status[]
field (which is array)
from data return by web::json::value::serialize()
?
Thank you.
回答1:
You don't have to call serialize
to access the json values. Once you have a json::value
, which holds a json object, you can traverse it to obtain inner objects and arrays as json::value
's:
json::value jvalue; //this is your initial value
// this new value will hold the whole 'data' object:
json::value data = jvalue.at(U("data"));
// read `timestamp` array from `data` and directly read
// the item at index 0 from it:
json::value timestamp = data.at(U("timestamp")).at(0);
// from `timestamp` (first item of timestmap array`)
json::value id = timestamp.at(U("_id"));
// print `id` as string
std::wcout << id.as_string() << std::endl;
// read `status` array first item and print it as string
json::value status = timestamp.at(U("status"));
std::wcout << status.at(0).as_string() << std::endl;
As you can guess from the code above, calls to at
can be chained together:
// read the `_id` value at once and print it as string
std::wcout << jvalue.at(U("data")).at(U("timestamp")).at(0).at(U("_id")).as_string() << std::endl;
Everything is well explained here.
来源:https://stackoverflow.com/questions/49933541/how-to-extract-specific-data-returned-from-webjsonvalueserialize-with-cp