2

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

1
  • 1
    You'll probably want to take a look at the JSON format on: json.org Commented Feb 22, 2011 at 13:19

1 Answer 1

4

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();
} 
Sign up to request clarification or add additional context in comments.

5 Comments

Doesn't handle control characters, which must be escaped with \uHHHH notation.
thanks, but is there some simple way, how to escape these characters?
@Fred: D'oh, i missed the "control character" part in the header, my bad.
@Ondra: fixed so it produces escaped versions of control characters too (for simplicity, also produces \uXXXX for \ and ").
When char is signed, many more chars will be less than 0x20 than you want to include. And I've never liked that + obfuscation. Why not int(s[i])?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.