34 #ifndef _vpJsonArgumentParser_h_
35 #define _vpJsonArgumentParser_h_
36 #include <visp3/core/vpConfig.h>
38 #if defined(VISP_HAVE_NLOHMANN_JSON)
39 #include <nlohmann/json.hpp>
40 #include <visp3/core/vpException.h>
52 nlohmann::json convertCommandLineArgument(
const std::string &arg)
54 nlohmann::json j = nlohmann::json::parse(arg);
64 nlohmann::json convertCommandLineArgument<std::string>(
const std::string &arg)
66 nlohmann::json j = arg;
151 vpJsonArgumentParser(
const std::string &description,
const std::string &jsonFileArgumentName,
const std::string &nestSeparator);
160 std::string help()
const;
180 const auto getter = [name,
this](nlohmann::json &j,
bool create) -> nlohmann::json *{
182 nlohmann::json *f = &j;
184 std::string name_copy = name;
186 while ((pos = name_copy.find(nestSeparator)) != std::string::npos) {
187 token = name_copy.substr(0, pos);
189 name_copy.erase(0, pos + nestSeparator.length());
190 if (create && !f->contains(token)) {
193 else if (!f->contains(token)) {
198 if (create && !f->contains(name_copy)) {
199 (*f)[name_copy] = {};
201 else if (!f->contains(name_copy)) {
204 f = &(f->at(name_copy));
208 parsers[name] = [¶meter, required, getter, name](nlohmann::json &j) {
209 const nlohmann::json *field = getter(j,
false);
210 const bool fieldHasNoValue = field ==
nullptr || (field !=
nullptr && field->is_null());
211 if (required && fieldHasNoValue) {
212 std::stringstream ss;
213 ss <<
"Argument " << name <<
" is required, but no value was provided" << std::endl;
216 else if (!fieldHasNoValue) {
217 field->get_to(parameter);
221 updaters[name] = [getter](nlohmann::json &j,
const std::string &s) {
222 nlohmann::json *field = getter(j,
true);
223 *field = convertCommandLineArgument<T>(s);
226 helpers[name] = [help, parameter, required]() -> std::string {
227 std::stringstream ss;
228 nlohmann::json repr = parameter;
229 ss << help << std::endl <<
"Default: " << repr;
231 ss << std::endl <<
"Required";
234 ss << std::endl <<
"Optional";
239 nlohmann::json *exampleField = getter(exampleJson,
true);
240 *exampleField = parameter;
251 void parse(
int argc,
const char *argv[]);
255 std::string description;
256 std::string jsonFileArgumentName;
257 std::string nestSeparator;
258 std::map<std::string, std::function<void(nlohmann::json &)>> parsers;
259 std::map<std::string, std::function<void(nlohmann::json &,
const std::string &)>> updaters;
260 std::map<std::string, std::function<std::string()>> helpers;
261 nlohmann::json exampleJson;
error that can be emitted by ViSP classes.
@ badValue
Used to indicate that a value is not in the allowed range.
Command line argument parsing with support for JSON files. If a JSON file is supplied,...
vpJsonArgumentParser & addArgument(const std::string &name, T ¶meter, const bool required=true, const std::string &help="No description")
Add an argument that can be provided by the user, either via command line or through the json file.