0

I'm building a web app, and need to be able to encode user-generated data as concisely as possible before transmitting it to my server. In the past I've used Flash, and it had a very neat system where for any class that you want to serialize, you could write a pair of functions that would describe exactly how to serialize the data. For example:

out.writeShort(session);
out.writeUnsignedInt(itemID);
out.writeObject(arbitraryData);
out.writeShort(score);

You would have to write an equivalent function to read bytes from the serialized data and build the class from it.

Once data is serialized it could be encoded into a Base64 string for safe network transmission to the server.

I can't figure out how to do this in Javascript? JSON is nice and easy but it's incredibly wasteful, sending all object key/value pairs, and unless I'm mistaken everything is encoded as a string? So the value false is encoded as the string "false"?

Any advice on how to implement this in Javascript would be greatly appreciated! Use of libraries is fine so long as they work both on Node and in browser.

Jim Sreven
  • 33
  • 6
  • 2
    propably would have used [DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) or just [Uint8Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) + [Bitwise Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) if you don't need some fancy syntax - it's possible to send them with ajax also – Endless Aug 19 '19 at 12:50
  • You can just write single string, instead of JSON, if you want and de-serialise it by just reading the same way you wrote it. Not sure why JSON is that bad, though - you can just prune your object to whatever is relevant. – VLAZ Aug 19 '19 at 12:50
  • Use a single string and use your own way of representing data , write a deserializer on the other side to decode it. For example if name = Prasanna, male = true can be encoded as "name=prasanna&male=(bool)true" convert this into Uint8Array or base64 string while transferring to server – Narasimha Prasanna HN Aug 19 '19 at 12:54

1 Answers1

0

Look at this answer. You can use BSON format (Binary JSON) and it doesn't have those features of JSON you mentioned.

Mustafa Shujaie
  • 1,447
  • 1
  • 16
  • 30