Json values validation #268
-
Hi Team, I have been exploring this awesome JSON library, and it's giving me what I am looking for. The help I am looking from you is, how to validate the JSON values. For example: Input Json If I pass the above JSON to decode into an emp class, then it works. But, my concern is how to validate the json values. I referred the documentation, but unable to find anything related to validating the values. Would request you to share some thoughts on this. --Dinesh |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If your input is a JSON array of employees, you can read the data row by row and reject bad records using the streaming (staj) API: #include <iostream>
#include <jsoncons/json.hpp>
namespace ns {
struct employee
{
std::string name;
uint64_t id;
int age;
};
}
JSONCONS_ALL_MEMBER_TRAITS(ns::employee,name,id,age)
int main()
{
std::string input = R"(
[
{
"name" : "John Smith",
"id" : 22,
"age" : 34
},
{
"name" : "",
"id" : 23,
"age" : 36
},
{
"name" : "Jane Doe",
"id" : 24,
"age" : 345
}
]
)";
jsoncons::json_cursor cursor(input);
auto view = jsoncons::staj_array<ns::employee>(cursor);
auto validate = [](const ns::employee& emp)
{
return !emp.name.empty() && (emp.age >= 16 && emp.age <= 68);
};
for (const auto& emp : view)
{
if (validate(emp))
{
std::cout << "Employee " << emp.id << " name: " << emp.name << ", age: " << emp.age << "\n";
}
else
{
std::cerr << "Reject " << emp.id << " at line " << cursor.line() << "\n";
}
}
std::cout << "\n\n";
} Output:
In a future release, we also intend to support schema validation. |
Beta Was this translation helpful? Give feedback.
If your input is a JSON array of employees, you can read the data row by row and reject bad records using the streaming (staj) API: