Skip to content

Method to get string representations of values #642

Description

@skaupper

I've come across occasions where I needed to "stringify" a single value.
I know that there is dump() to serialize the whole object but it doesn't work as I would expected it (string values are enclosed in double quotes). Actually I know dump() is not meant for representing a single value as string that's why I want to suggest to add a method responsible for converting the value to a string.

My own implementation that I'm currently using looks like following:

inline std::string to_string(const json &j)
{
    auto tmp = j.dump();
    
    if (j.type() == json::value_t::string) {
        return tmp.substr(1, tmp.size() - 2);
    } else {
        return tmp;
    }
}

So, basically I want code like this to work.

    json j = "{\"field\": 1234}"_json;
    std::string s = j["field"].to_string();

Could you imagine having such a method?
Maybe it is possible to specialize the get() method to get such a behaviour?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions