Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
Getfree opened this issue Apr 26, 2017 · 6 comments
Closed

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

Getfree opened this issue Apr 26, 2017 · 6 comments
Assignees
Milestone

Comments

@Getfree
Copy link

Getfree commented Apr 26, 2017

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
@nlohmann
Copy link
Owner

Have a look at the value function.

@Getfree
Copy link
Author

Getfree commented Apr 26, 2017

You mean the iterator's value() method?
That method doesn't take any optional arguments.

@Getfree
Copy link
Author

Getfree commented Apr 26, 2017

Oh, that's great. I missed that one completely. I couldn't find it in anywhere in the documentation.

@Getfree
Copy link
Author

Getfree commented Apr 26, 2017

Let's change this request to:
"Add json.value() to the list in https://nlohmann.github.io/json/"

@nlohmann nlohmann self-assigned this May 5, 2017
@nlohmann nlohmann added this to the Release 3.0.0 milestone May 5, 2017
@nlohmann
Copy link
Owner

nlohmann commented May 5, 2017

Thanks for the hint. I mentioned the value function on the documentation main page.

@nlohmann nlohmann closed this as completed May 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants