/* Read lines of text and add them as key/value objects in JSON. Then print the JSON. */ #include "nlohmann/json.hpp" #include #include #include using namespace std; using nlohmann::json; int main() { string key, val; double v; vector sv; vector bv; vector dv; istringstream ss; string line; string s; size_t i; json js; /* Read in lines of text. If there are two words, then store a key/value pair in the json. If the value can be interpreted as a double, then store it as a double. Otherwise, store it as a string. If there are more than two words, then have the value be an array. */ js = json::object(); /* Read the line and turn it into a vector of words, bools and doubles. */ while (getline(cin, line)) { sv.clear(); bv.clear(); dv.clear(); ss.clear(); ss.str(line); while (ss >> s) { v = 0; sv.push_back(s); bv.push_back(sscanf(s.c_str(), "%lf", &v) == 1); dv.push_back(v); } /* Set js[key] to val, using sscanf to see if val is a double or string */ if (sv.size() == 2) { if (bv[1]) { // It's a double. js[sv[0]] = dv[1]; } else { // It's a string. js[sv[0]] = sv[1]; } /* Otherwise set js[key] to be an array of values. */ } else if (sv.size() > 2) { key = sv[0]; js[key] = json::array(); for (i = 1; i < sv.size(); i++) { if (bv[i]) { // It's a double. js[key].push_back(dv[i]); } else { // It's a string. js[key].push_back(sv[i]); } } } } /* Print it out. */ cout << js << endl; return 0; }