LINUX.ORG.RU

История изменений

Исправление yoghurt, (текущая версия) :

#include <map>
#include <string>
#include <iostream>
#include <sstream>

class JSON {
protected:
   std::map<std::string, std::string> fields;

public:
   JSON& operator() (const std::string &k, const std::string &v) {
      fields[k] = "\"" + v + "\"";
      return *this;
   }

   JSON& operator() (const std::string &k, const JSON &j) {
      fields[k] = j.str();
      return *this;
   }

   std::string str() const {
      std::stringstream ofs;
      auto it = fields.begin();
      ofs << "{ " << "\"" << it->first << "\" : " << it->second;
      ++it;
      for (; it != fields.end(); ++it) {
         ofs << ", \"" << it->first << "\" : " << it->second;
      }
      ofs << " }";
      return ofs.str();
   }
};

inline JSON j() {
   return JSON();
}

int main(int argc, char *argv[]) {
   JSON json = j()
      ("foo", "bar")
      ("LOR", "tort")
      ("nested", j()
       ("works", "fine")
       ("so",    "good"));

   std::cout << json.str() << std::endl;
   return 0;
}
$ ./a.out 
{ «LOR» : «tort», «foo» : «bar», «nested» : { «so» : «good», «works» : «fine» } }

Исходная версия yoghurt, :

Вам бы всё лишь бы что-нибудь расширить

#include <map>
#include <string>
#include <iostream>
#include <sstream>

class JSON {
protected:
   std::map<std::string, std::string> fields;

public:
   JSON& operator() (const std::string &k, const std::string &v) {
      fields[k] = "\"" + v + "\"";
      return *this;
   }

   JSON& operator() (const std::string &k, const JSON &j) {
      fields[k] = j.str();
      return *this;
   }

   std::string str() const
   {
      std::stringstream ofs;
      auto it = fields.begin();
      ofs << "{ " << "\"" << it->first << "\" : " << it->second;
      ++it;
      for (; it != fields.end(); ++it) {
         ofs << ", \"" << it->first << "\" : " << it->second;
      }
      ofs << " }";
      return ofs.str();
   }
};

inline JSON j() {
   return JSON();
}

int main(int argc, char *argv[]) {
   JSON json = j()
      ("foo", "bar")
      ("LOR", "tort")
      ("nested", j()
       ("works", "fine")
       ("so",    "good"));

   std::cout << json.str() << std::endl;
   return 0;
}
$ ./a.out 
{ «LOR» : «tort», «foo» : «bar», «nested» : { «so» : «good», «works» : «fine» } }