daisy
daisy

Reputation: 23489

How can I ask jsoncpp to encode unicode strings?

I'm using the following code to test jsoncpp

#include <json/json.h>
#include <iostream>

using namespace std;

int main(int argc, char ** argv)
{
    Json::Value root;
    root["test"] = "中文测试123";

    Json::StyledWriter styledWriter;
    cout << styledWriter.write(root) << endl;

    return 0;
}

And the output is like this

{
   "test" : "中文测试123"
}

I'm wondering if jsoncpp can escape those unicode to \\uXXXX?

I've tried both FastWriter and StyledWriter, non of them works

Upvotes: 1

Views: 2976

Answers (1)

Pamela
Pamela

Reputation: 649

It depends on which version you are using.


using jsoncpp 1.8.3

{
   "test" : "中文测试123"
}

using jsoncpp 1.8.4

released on Dec 21, 2017
related commit: Serialize UTF-8 string with Unicode escapes (#687)

{
   "test" : "\u4e2d\u6587\u6d4b\u8bd5123"
}

using jsoncpp 1.9.2

released on Nov 14, 2019
related commit: Added emitUTF8 setting. (#1045)

#include <json/json.h>
#include <iostream>

void print_json(const Json::Value& value, bool emitUTF8) {
    Json::StreamWriterBuilder builder;
    builder.settings_["emitUTF8"] = emitUTF8;
    std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
    writer->write(value, &std::cout);
}

int main() {
    Json::Value root;
    root["test"] = "中文测试123";

    print_json(root, true);
    std::cout << std::endl;
    print_json(root, false);
}

/*
output:
{
    "test" : "中文测试123"
}
{
    "test" : "\u4e2d\u6587\u6d4b\u8bd5123"
}
*/

Upvotes: 2

Related Questions