开发者

JSONify string in C++

开发者 https://www.devze.com 2023-02-12 20:32 出处:网络
In my program I need to output simle JSON data. I looked at many libraries for JSON in c++, they are too complex for my task. Is there some easier way, how to create JSON-safe string from any c++ stri

In my program I need to output simle JSON data. I looked at many libraries for JSON in c++, they are too complex for my task. Is there some easier way, how to create JSON-safe string from any c++ string?

开发者_运维技巧
string s = "some potentially dangerous string";
cout << "{\"output\":\"" << convert_string(s) << "\"}";

How would function convert_string(string s) look like?

thanks


If your data is in UTF-8, per the string graph on 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();
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号