Home > database >  Reading array elements from string
Reading array elements from string

Time:09-26

I have an array of pairs<string,string> encoded into a database string, I am attempting to access the array element to eventually construct a std::map<std::string,std::string> but attempting to acccess array elements from my string gives me an exception

bool
test_json_map_string_string() {

        std::string database_string { "[{\"bootloaderVersion\":\"4\"},{\"date\":\"2021/09/24\"},{\"type\":\"5\"},{\"version\":\"175\"}]"};

        // database_string=[{"bootloaderVersion":"4"},{"date":"2021/09/24"},{"type":"5"},{"version":"175"}]
        std::cout << "database_string=" << database_string << std::endl;

        using json = nlohmann::json;

        try {
                json object_array = json::array();
                json json_str( database_string );

                json_str.get_to(object_array);

                // object_array.size=1 object_array.is_array=0
                std::cout << "object_array.size=" << object_array.size() << " object_array.is_array=" << object_array.is_array() << std::endl;

                for( size_t index = 0; index < object_array.size();   index ) {
                         // object_array[0] =
                        std::cout << "object_array[" << index << "] = " << object_array[index] << std::endl;
                }
                return true;
        } catch( const std::exception& except ) {
                // except=[json.exception.type_error.305] cannot use operator[] with a numeric argument with string
                std::cerr << "except=" << except.what() << std::endl;
                return false;
        }
}

How do I initialize nlohmann::json with a std::string and then access array elements within it? The method I used does not seem to recognize the array.

Best regards

CodePudding user response:

get_to() is an assignment, and does not parse. What you want is:

json object_array = json::parse(database_string);

Example: https://godbolt.org/z/WsrvEc5MK

  • Related