nlohmann / json

JSON for Modern C++
https://json.nlohmann.me
MIT License
42.01k stars 6.63k forks source link

Can't support convert the type? std::string json_str = R"({"value": "3.1415"})"; float value = j["value"].get<float>(); #3984

Closed TerryHoCQ closed 11 months ago

TerryHoCQ commented 1 year ago

Description

include

include

include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() { std::string json_str = R"({"value": "3.1415"})"; json j = json::parse(json_str);

float value = j["value"].get<float>();
std::cout << "Value: " << value << std::endl;

std::string float_str = "3.1415926";
float float_num = std::stof(float_str);
std::cout << "Float: " << float_num << std::endl;

return 0;

}

Reproduction steps

include

include

include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() { std::string json_str = R"({"value": "3.1415"})"; json j = json::parse(json_str);

float value = j["value"].get<float>();
std::cout << "Value: " << value << std::endl;

std::string float_str = "3.1415926";
float float_num = std::stof(float_str);
std::cout << "Float: " << float_num << std::endl;

return 0;

}

Expected vs. actual results

include

include

include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() { std::string json_str = R"({"value": "3.1415"})"; json j = json::parse(json_str);

float value = j["value"].get<float>();
std::cout << "Value: " << value << std::endl;

std::string float_str = "3.1415926";
float float_num = std::stof(float_str);
std::cout << "Float: " << float_num << std::endl;

return 0;

}

Minimal code example

#include <iostream>
#include <string>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

int main() {
    std::string json_str = R"({"value": "3.1415"})";
    json j = json::parse(json_str);

    float value = j["value"].get<float>();
    std::cout << "Value: " << value << std::endl;

    std::string float_str = "3.1415926";
    float float_num = std::stof(float_str);
    std::cout << "Float: " << float_num << std::endl;

    return 0;
}

Error messages

No response

Compiler and operating system

vs20019+WIN10

Library version

v3.11.2

Validation

nlohmann commented 1 year ago

In order to asses your issue, we need the following information:

TerryHoCQ commented 1 year ago
float value = j["value"].get<float>();

float value = j["value"].get(); //this will throw exception, the original type in JSON TXT R"({"value": "3.1415"})" is string, we try to convert string to a float.

nlohmann commented 1 year ago

The library does not provide string-to-float conversion.