Saturday, December 3, 2016

6 function of JSON render matching 6 type in JSON variant


#pragma once
#include <string>
#include <sstream>
#include "JSONWrapper.hpp"
#include "join.hpp"
#include "fold.hpp"
#include <iomanip>

using namespace std;

string render_bool(bool b) { return b ? "true" : "false"; }
string render_double(double d) { return to_string(d); }
string render_null(nullptr_t) { return "null"; }
string render_string(const string& s)
{
 stringstream ss;
 ss << std::quoted(s);
 return ss.str();
}

string render_json_value(const JSONValue& jsv);

string render_object(const JSONObject& obj)
{
 return string{ "[" }+
  join(obj.begin(), obj.end(), string{ "." },
   [](const JSONObject::value_type& jsv) {
  return render_string(jsv.first) + ":" + render_json_value(jsv.second);
 }) + "]";
}

string render_array(const JSONArray& a)
{
 return string{ "[" }+
  join(a.begin(), a.end(), string{ "," },
   [](const JSONValue& jsv) {
  return render_json_value(jsv);
 }) + "]";
}

string render_json_value(const JSONValue& jsv)
{
 return fold(jsv,
  render_bool, render_double, render_string,
  render_null, render_array, render_object);
}

No comments:

Post a Comment