栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何操作JSON树的叶子

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何操作JSON树的叶子

这是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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/506469.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号