Skip to content

RFC: fluent parsing interface #1023

Description

@markand

Feature Request

I'm searching a convenient way for destructuring data where I can have the following requirements:

  • I do not need intermediate value, result should be returned in any case
  • If I require a value from a JSON object and...
    • ... value is not defined: I throw a custom exception
    • ... value is not the good type: I throw an exception
  • If I search an optional value and...
    • ... value is not defined: I return a default value given
    • ... value is not the good type: I throw an exception

Final code should look like this:

const nlohmann::json json{
    { "hostname", "localhost" }
};

const parser ps(json);

// s is a object I want to convert from JSON.
server s;
s.set_host(ps.get<std::string>("hostname")
             .error<std::invalid_argument>("invalid hostname"));
s.set_port(ps.get<std::string>("port")
             .optional("irc")
             .error<std::runtime_error>("invalid port number"));

In this case, I require hostname property, if it's missing std::invalid_argument("invalid hostname") will be thrown. For port property, if the value is not defined, I return irc otherwise if it's defined in the wrong type I throw std::invalid_argument("invalid port number").

The code is not complete yet, but you can see a simple POC in this gist:

https://gist.github.com/markand/45c9f6a3f9239802850badd8869117e3

What are your thoughts? How do you usually deserialize unverified input?

Metadata

Metadata

Assignees

No one assigned

    Labels

    state: needs more infothe author of the issue needs to provide more details

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions