0

I'm having an issue with my code for jSon object conversion. I am trying to write a loop that takes in a vector and if the vector has an inversion then store that in a jSon Object. The only real problem I am having is the correct output. I am getting an error when trying to use a variable as key value when expecting a string. My main question is how to do I convert my integer to a string so the code accepts it and prints properly?

for(auto j = 0; j <= myvec.size(); j++){
    m = j+1;
    if(m > myvec.size()){
        break;
    }
    if(name == metad){
        break;
    }
    if(myvec[m] != 0){
        if(myvec[j] > myvec[m]){
            jcount = j;
            jsonresult.emplace_back(nlohmann::json::object_t::value_type(j,{ myvec[j], myvec[m]}));
            count++;
        }

The main problem is in the emplace_back line where it will not let me use j as the proper key value resulting in the error

error: no matching function for call to ‘std::pair<const std::__cxx11::basic_string<char>, nlohmann::basic_json<> >::pair(int&, <brace-enclosed initializer list>)’
     jsonresult.emplace_back(nlohmann::json::object_t::value_type(j,{myvec[j], myvec[m]}));

So I guess my question is how do I get it to store the dynamic variable correctly so my code then outputs this

1":[811700988,797039],"2":[797039,-1680733532]

instead of

[
  2,
  797039,
  -1680733532
]

Appreciate any help, thank you!

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

If you're using C++11 you can use to_string() to convert the index to a string for use as the object key. And you can assign a vector to the property in the JSON object.

if (myvec[m] != 0 && myvec[j] > myvec[m]) {
    vector<int> pair{myvec[j], myvec[m]};
    jsonresult[to_string(j)] = pair;
}

emplace_back() is for appending to a JSON array, not object.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Yeah to_string() ended up being the solution so if anyone else is having the issue this is the answer! Thank you for the help. – user3712347 Feb 22 '19 at 05:34