0

i am using a cpp crow library and i am having difficulty in accessing individual objects i am attaching my code here.

CROW_ROUTE(app,"/hello/<string>")
([](string name){
    crow::json::wvalue x;
  x["name"] = "llllds";
  x["Town"] = "Texas";
  x["nickname"] = "drax";
  x["father"] = "Nethan";
  
  if (name == "Nothing")
       cout << "Bad Responce";
    std::ostringstream os;
   cout << name << " is the required query";
   val = x[name];
   return val;

And i want to return my name can anyone help me with this. Thanks in advance

1 Answers1

0

I used JSON for Modern C++ within crow (https://github.com/nlohmann/json) Here is an example CROW_ROUTE I wrote

CROW_ROUTE(app, "/palindromes/<string>/<string>")([](const request &req, response &res, string ID, string words){
    palindromeHash.insert({ID, words}); //ignore this
    nlohmann::json x;
    x = getPalindromes(palindromeHash.at(ID));
    palindromeHash.erase(ID); //ignore this
    res.sendJSON(x);
});

//getPalindromesFunction()

nlohmann::json getPalindromes(string data){
    nlohmann::json x;
    unordered_map<string, bool> hashmap;
    string word = "";
    std::string::size_type i = data.find("%20");
    while (i != std::string::npos){
        data.erase(i, 3);
        data.insert(i, " ");
        i = data.find("%20", i);
    }
    for(int i = 0; i < data.size(); i++){
        if(data[i] == ' '){
            hashmap.insert({word, true});
            word = "";
        }
        else{
            word += data[i];
        }
    }
    string temp;
    vector<string> words;
    int numValid = 0;
    for(auto& i: hashmap){
        temp = i.first;
        reverse(temp.begin(), temp.end());
        auto got = hashmap.find(temp);
        if(got != hashmap.end()){
            words.push_back(i.first);
            numValid++;
        }
    }
    x["words"] = words;
    x["numValid"] = numValid;
    return x;
}

As you can see it returns a JSON object x that holds palindromes. The sendJSON() function is something I added to crow_all.h. Add it under the struct response section on line 7215

void sendJSON(const nlohmann::json& data){
    std::string response = data.dump();

    add_header("Access-Control-Allow-Origin", "*");
    add_header("Content-Type", "text/html");
    write(response);
    end();
}

Remember to include "json.h" in both main.cpp and crow_all.h. The res.sendJSON will send it to my JS file which can loop through the JSON with ease.

$.get("/palindromes/" + ID + "/" + curr_line, {}, function(response){
        let x = JSON.parse(response); //This will allow JS to read the C++ JSON
        for(let i = 0; i < x.words.length; i++){
            term.write(x.words[i] + "\r\n");
        }
}
NeonFire
  • 186
  • 2
  • 7