简单的JSON字符串转义为C ++? [英] Simple JSON string escape for C++?

查看:692
本文介绍了简单的JSON字符串转义为C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的程序,输出简单的JSON字符串,我手动并置在一起,并通过std :: cout流输出(输出真的是那么简单),但我有字符串可以包含双引号,卷曲大括号和其他可能破坏JSON字符串的字符。所以我需要一个库(或一个函数更准确)转义字符串相应的JSON标准,尽可能轻量级,没有更多,没有更少。



很少有库用于将整个对象编码为JSON,但是我的程序是900行的cpp文件,我宁愿不依赖于一个比我的程序只是为了实现这样简单的程序。 / p>

解决方案

更新:不要使用! vog提供了一个更完整(同样紧凑)的解决方案: http://stackoverflow.com/a/33799784

下面是一个非常简单的开始,它不处理无效的unicode字符。如果你不希望在你的输出中有它们,请随意使用...

  #include< string> ; 
#include< sstream>

std :: string escapeJsonString(const std :: string& input){
std :: ostringstream ss;
for(auto iter = input.cbegin(); iter!= input.cend(); iter ++){
// C ++ 98/03:
// for(std: :string :: const_iterator iter = input.begin(); iter!= input.end(); iter ++){
switch(* iter){
case'\\':ss< < \\\\;打破;
case'':ss< <\\\;打破;
case'/':ss<< \\ /;打破;
case'\b':ss<< \\b;打破;
case'\f':ss<< \\F;打破;
case'\\\
':ss<< \\\\
;打破;
case'\r':ss<< \\r;打破;
case'\t':ss<< \\t;打破;
默认值:ss<< * iter;打破;
}
}
return ss.str();
}


I'm having a very simple program that outputs simple JSON string that I manually concatenate together and output through the std::cout stream (the output really is that simple) but I have strings that could contain double-quotes, curly-braces and other characters that could break the JSON string. So I need a library (or a function more accurately) to escape strings accordingly to the JSON standard, as lightweight as possible, nothing more, nothing less.

I found a few libraries that are used to encode whole objects into JSON but having in mind my program is 900 line cpp file, I rather want to not rely on a library that is few times bigger then my program just to achieve something as simple as this.

解决方案

Update: Don't use this! vog provides a much more complete (and equally compact) solution down below: http://stackoverflow.com/a/33799784

Here's a very simple start, it doesn't handle invalid unicode characters though. If you don't expect any of them in your output, feel free to use this...

#include <string>
#include <sstream>

std::string escapeJsonString(const std::string& input) {
    std::ostringstream ss;
    for (auto iter = input.cbegin(); iter != input.cend(); iter++) {
    //C++98/03:
    //for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) {
        switch (*iter) {
            case '\\': ss << "\\\\"; break;
            case '"': ss << "\\\""; break;
            case '/': ss << "\\/"; break;
            case '\b': ss << "\\b"; break;
            case '\f': ss << "\\f"; break;
            case '\n': ss << "\\n"; break;
            case '\r': ss << "\\r"; break;
            case '\t': ss << "\\t"; break;
            default: ss << *iter; break;
        }
    }
    return ss.str();
}

这篇关于简单的JSON字符串转义为C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆