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

How to get the length of a JSON string without retrieving its std::string? #897

Closed
ibc opened this issue Dec 31, 2017 · 9 comments
Closed
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation

Comments

@ibc
Copy link

ibc commented Dec 31, 2017

Basically that. I know that a json object holds a string and I need to know its length, hopefully without having to convert it into a C++ std::string.

Is it possible?

@ijijn
Copy link

ijijn commented Jan 1, 2018

Hi. How are you getting your json object?

Not sure that this helps, but if you do something like:
const auto name{ j.value("name", "") }; (using the default-value hint technique for a string_t type)
you can then use name.length() to get the length without additional casting. That's how I usually do this sort of thing anyway, but I'm very new to the library ... and loving it!

@ibc
Copy link
Author

ibc commented Jan 1, 2018

Thanks @ijijn. Not valid for my use case, but good to know.

@rexdf
Copy link

rexdf commented Jan 2, 2018

  • value access
    -1. get – get a value
    -2. get_ptr – get a value pointer
    -3. get_ref – get a value reference

string json object seems to be internally implemented in std::string

@ibc
Copy link
Author

ibc commented Jan 2, 2018

Great. Perhaps this should be documented?

@rexdf
Copy link

rexdf commented Jan 2, 2018

@ibc
Copy link
Author

ibc commented Jan 2, 2018

Thanks @rexdf, my absolute fault.

@ibc ibc closed this as completed Jan 2, 2018
@nlohmann
Copy link
Owner

nlohmann commented Jan 4, 2018

For reference:

json j_string = "foo bar";
size_t len = j_string.get_ref<json::string_t&>().size();

@nlohmann nlohmann added kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation labels Jan 4, 2018
@ibc
Copy link
Author

ibc commented Jan 4, 2018

Thanks. Would that also work if json j_string = 1234?

@nlohmann
Copy link
Owner

nlohmann commented Jan 4, 2018

No. You would get an exception:

[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind: question solution: proposed fix a fix for the issue has been proposed and waits for confirmation
Projects
None yet
Development

No branches or pull requests

4 participants