Repository navigation
Type Conversion #779
Description
Activity
The library does not provide such conversions.
You may need something like
#include "json.hpp" using json = nlohmann::json; int main() { json j = {{"number", "9"}}; int i = std::stoi(j["number"].get_ref<std::string&>()); }
Thank you for the quick response. Great library.
I have one more question. What is the difference between?:
j["number"].get_ref<std::string&>() j["number"] j.at("number")They all seem to do the same thing and return a reference.
j.at("number")andj["number"]will both return a reference to thejsonobject corresponding to the key"number"if it exists. If not, thenatwill throw, as will[]on aconstjobject. For a non-constj, it will create a new key with anullvalue.Then
.get_ref<std::string&>()returns a reference to thestd::stringvalue in the returned object, assuming that is its type.So, what will tmp be, string& or string?:
auto tmp = j.at("number");This is a copy,
autonever deduces to a reference. If you want a reference, useauto &tmp = j.at("number");So
atand[]can both return a reference or a copy of the value. Why did you say it returns the reference to the key?They always return a reference, which is then copied if you don't use
&, becauseautodeducesjsoninstead ofjson &orconst json &. When you add the&, it deducesjson &orconst json &depending on whether or notjisconst.- addedsolution: proposed fixa fix for the issue has been proposed and waits for confirmationa fix for the issue has been proposed and waits for confirmation
on Oct 13, 2017 Can I close this issue?
💤 I closed this issue due to inactivity. Please feel free to add a comment and I shall reopen it.
@nlohmann
so, if I gotnlohmann::json json, that representMyStruct, but someone put"value": "5", instead of"value": 5,
thenauto myStruct = json.get<MyStruct>()will throw exception?what would be the proper way to solve this,
implementto_jsonandfrom_jsonmanually, instead of one ofNLOHMANN_DEFINE_TYPE...()?
how safe function would looks like (that could work with bothintandstring) instead of
type_to.val = json_from.value("val", default_obj.val);Or there is something better, that leaves autogenerating with
NLOHMANN_DEFINE_TYPE...()?
Is there a way to convert a string value to a number value or vice versa?
For example:
I figured this word work, but it doesn't:
j.at( "number" ).get<int>();Do I just have to grab it as a string and convert myself, or is there a better way?