这是C ++中的直接方法:
#include <fstream>#include "JSON.hpp"#include <boost/algorithm/string/regex.hpp>#include <boost/range/adaptors.hpp>#include <boost/phoenix.hpp>static std::vector<std::wstring> readRareWordList(){ std::vector<std::wstring> result; std::wifstream ifs("testcases/rarewords.txt"); std::wstring line; while (std::getline(ifs, line)) result.push_back(std::move(line)); return result;}struct RareWords : boost::static_visitor<> { ///////////////////////////////////// // do nothing by default template <typename T> void operator()(T&&) const { } ///////////////////////////////////// // recurse arrays and objects void operator()(JSON::Object& obj) const { for(auto& v : obj.values) { //RareWords::operator()(v.first); boost::apply_visitor(*this, v.second); } } void operator()(JSON::Array& arr) const { int i = 0; for(auto& v : arr.values) { if (i++) // skip the first element in all arrays boost::apply_visitor(*this, v); } } ///////////////////////////////////// // do replacements on strings void operator()(JSON::String& s) const { using namespace boost; const static std::vector<std::wstring> rareWords = readRareWordList(); const static std::wstring replacement = L"__RARE__"; for (auto&& word : rareWords) if (word == s.value) s.value = replacement; }};int main(){ auto document = JSON::readFrom(std::ifstream("testcases/test3.json")); boost::apply_visitor(RareWords(), document); std::cout << document;}假设您要替换所有字符串值,并且仅匹配整个字符串。略微适应了评论。
您可以通过更改regex或regex标志轻松地使这种大小写不敏感,匹配字符串中的单词等。
包括JSON.hpp /
cpp的完整代码在这里:https :
//github.com/sehe/spirit-v2-json/tree/16093940



