JSONify C ++中的字符串

时间:2011-02-22 13:17:00

标签: c++ json

在我的程序中,我需要输出simle JSON数据。我在c ++中查看了许多用于JSON的库,它们对于我的任务来说太复杂了。有没有更简单的方法,如何从任何c ++字符串创建JSON安全字符串?

string s = "some potentially dangerous string";
cout << "{\"output\":\"" << convert_string(s) << "\"}";

convert_string(string s)的函数如何?

感谢

1 个答案:

答案 0 :(得分:4)

如果您的数据是UTF-8,则按照http://json.org/上的字符串图表

#include <sstream>
#include <string>
#include <iomanip>
std::string convert_string(std::string s) {
    std::stringstream ss;
    for (size_t i = 0; i < s.length(); ++i) {
        if (unsigned(s[i]) < '\x20' || s[i] == '\\' || s[i] == '"') {
            ss << "\\u" << std::setfill('0') << std::setw(4) << std::hex << unsigned(s[i]);
        } else {
            ss << s[i];
        }
    } 
    return ss.str();
} 
相关问题