Parsing json messagepack data in javascript

1.1k Views Asked by At

I'm sending json data to a websocketpp server with messagepack using kawanet/msgpack-lite (javascript) on the client and msgpack/msgpack-c (C++) to unpack it and nlohmann/json to parse it on the server. This goes fine.

But I'm apparently using messagepack the wrong way since I can't parse the returned data correctly.

Server:

if (jdata["type"] == "msg") {
    std::stringstream buffer;
    std::string clientmsg = jdata["data"];
    jdata["cnt"] = clientmsg.length();
    msgpack::pack(buffer, jdata.dump());
    size_t plen = buffer.tellp();
    msg->set_payload(&buffer, plen);
    m_server.send(hdl, msg);
}

Client:

reader.onload = function (e) {
    console.log("FileReader.onload(): " + reader.result);
    var decoded_message = msgpack.decode(reader.result);
}
reader.readAsText(e.data);

It fails on msgpack.decode() with

Uncaught Error: Invalid type: 0xh

When sending json as string in set_payload()

msg->set_payload(jdata.dump());

it's transmitted fine

FileReader.onload(): {"cnt":4,"data":"test","type":"msg"}
2

There are 2 best solutions below

3
zaphoyd On

The address of a std::stringstream is not a pointer to its underlying buffer.

Try: msg->set_payload(buffer.str());.

1
Niels Lohmann On

If it helps: nlohmann/json now supports MessagePack (and CBOR), so you now can realize your scenario completely withing nlohmann/json. See https://github.com/nlohmann/json#binary-formats-cbor-and-messagepack for examples.