#include <libsolutil/JSON.h>
#include <libsolutil/CommonIO.h>
#include <boost/algorithm/string/replace.hpp>
#include <sstream>
#include <map>
#include <memory>
using namespace std;
static_assert(
(JSONCPP_VERSION_MAJOR == 1) && (JSONCPP_VERSION_MINOR == 9) && (JSONCPP_VERSION_PATCH == 3),
"Unexpected jsoncpp version: " JSONCPP_VERSION_STRING ". Expecting 1.9.3."
);
namespace solidity::util
{
namespace
{
class StreamWriterBuilder: public Json::StreamWriterBuilder
{
public:
explicit StreamWriterBuilder(map<string, Json::Value> const& _settings)
{
for (auto const& iter: _settings)
this->settings_[iter.first] = iter.second;
}
};
class StrictModeCharReaderBuilder: public Json::CharReaderBuilder
{
public:
StrictModeCharReaderBuilder()
{
Json::CharReaderBuilder::strictMode(&this->settings_);
}
};
string print(Json::Value const& _input, Json::StreamWriterBuilder const& _builder)
{
stringstream stream;
unique_ptr<Json::StreamWriter> writer(_builder.newStreamWriter());
writer->write(_input, &stream);
return stream.str();
}
bool parse(Json::CharReaderBuilder& _builder, string const& _input, Json::Value& _json, string* _errs)
{
unique_ptr<Json::CharReader> reader(_builder.newCharReader());
return reader->parse(_input.c_str(), _input.c_str() + _input.length(), &_json, _errs);
}
void removeNullMembersHelper(Json::Value& _json)
{
if (_json.type() == Json::ValueType::arrayValue)
for (auto& child: _json)
removeNullMembersHelper(child);
else if (_json.type() == Json::ValueType::objectValue)
for (auto const& key: _json.getMemberNames())
{
Json::Value& value = _json[key];
if (value.isNull())
_json.removeMember(key);
else
removeNullMembersHelper(value);
}
}
}
Json::Value removeNullMembers(Json::Value _json)
{
removeNullMembersHelper(_json);
return _json;
}
string jsonPrettyPrint(Json::Value const& _input)
{
return jsonPrint(_input, JsonFormat{ JsonFormat::Pretty });
}
string jsonCompactPrint(Json::Value const& _input)
{
return jsonPrint(_input, JsonFormat{ JsonFormat::Compact });
}
string jsonPrint(Json::Value const& _input, JsonFormat const& _format)
{
map<string, Json::Value> settings;
if (_format.format == JsonFormat::Pretty)
{
settings["indentation"] = string(_format.indent, ' ');
settings["enableYAMLCompatibility"] = true;
}
else
settings["indentation"] = "";
StreamWriterBuilder writerBuilder(settings);
string result = print(_input, writerBuilder);
if (_format.format == JsonFormat::Pretty)
boost::replace_all(result, " \n", "\n");
return result;
}
bool jsonParseStrict(string const& _input, Json::Value& _json, string* _errs )
{
static StrictModeCharReaderBuilder readerBuilder;
return parse(readerBuilder, _input, _json, _errs);
}
}