Skip to content

Request: Object.at() with default return value #570

Description

@Getfree

On many implementations of dictionary-like structures, we have an at/get method that works like this:
Object.at("key",defaultValue)
i.e. if there's no key "key", then this would return defaultValue.

Could we have something similar in this library?

Here is a possible implementation:

template<typename returnType>
returnType at(const typename object_t::key_type& key, const returnType& _default){
	if( is_object() ){
		JSON_TRY{
			return m_value.object->at(key) ;
		}
		JSON_CATCH( std::out_of_range& ){
			return _default ;
		}
	}else{
		JSON_THROW(std::domain_error("cannot use at() with " + type_name()));
	}
}

Usage example:

json js ;
js.at("key", 5) ; // "key" is expected to hold something convertible to `int`, otherwise 5 is returned

Activity

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

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions