title: Better way to de/serialize an Thrift object from/to JSON using the pure Javascript library?
body: <p>I have a web server returning an thrift object serialized used the JSON protocol to a client html page using the pure Javascript Thrift library (<a href="https://github.com/apache/thrift/tree/master/lib/js/src" rel="nofollow"><code>thrift.js</code></a>). </p>
  
  <p>The server for example:</p>
  
  <pre><code>from MyThriftFile.ttypes import ThriftClass
  from thrift import TSerialization
  from thrift.protocol import TJSONProtocol
  
  thrift_obj = new ThriftClass()
  result = TSerialization.serialize(
      thrift_obj,
      protocol_factory=TJSONProtocol.TJSONProtocolFactory())
  
  return result
  </code></pre>
  
  <p>Now in the C#, Python, Java, and even the node.js Thrift libraries there is some form of this generic TSerialization or TDeserialization utlity and its more or less implemented like so:</p>
  
  <pre><code>def deserialize(base,
          buf,
          protocol_factory=TBinaryProtocol.TBinaryProtocolFactory()):
  
      transport = TTransport.TMemoryBuffer(buf)
      protocol = protocol_factory.getProtocol(transport)
      base.read(protocol)
      return base
  </code></pre>
  
  <p>So it gets it data, loads it up into a throw away transport (because we are not going to send this information anywhere), creates a new protocol object for encoding this data, and finally the actual thrift object reads this data to populate itself.</p>
  
  <p>The pure javacript library however seems to lack this functionality. I understand why the client library only support the JSON protocol (web pages don't deal in raw binary data) but why not method for de/serialization from/to JSON?</p>
  
  <p>I made my own method for doing the job but it seems hacky. Anyone have a better trick?</p>
  
  <pre><code>$(document).ready(function() {
      $.get("www.mysite.com/thrift_object_i_want/", function(data,     status) {
          var transport = new Thrift.Transport();
          var protocol  = new Thrift.Protocol(transport);
  
          // Sets the data we are going to read from.
          transport.setRecvBuffer(data);
  
          // This is basically equal to
          // rawd = data
          rawd = transport.readAll();
  
          // The following is lifited from 
          // readMessageBegin().
          // These params I am setting are private memeber
          // vars that protocol needs set in order to read
          // data set in setRevBuff()
          obj = $.parseJSON(rawd);
          protocol.rpos = []
          protocol.rstack = []
          protocol.rstack.push(obj)
  
          // Now that the protocl has been hacked to function
          // populate our object from it
          tc = new ThriftClass();
          tc.read(protocol);
  
          // u is now a js object equal to the python object
      });
  });
  </code></pre>