title: how to serialize arbitrary file types to json string in python
body: <p>My server is going to be sending a JSON, serialized as a string, through a socket to another client machine. I'll take my final json and do this:</p>
  
  <pre><code>import json
  python_dict_obj = { "id" : 1001, "name" : "something", "file" : &lt;???&gt; }
  serialized_json_str = json.dumps(python_dict_obj)
  </code></pre>
  
  <p>I'd like to have one of the fields in my JSON have the value that is a file, encoded as a string. </p>
  
  <p>Performance-wise (but also interoperability-wise) what is the best way to encode a file using python? Base64? Binary? Just the raw string text? </p>
  
  <p>EDIT - For those suggestion base64, something like this?</p>
  
  <pre><code># get file
  import base64
  import json
  
  with open(filename, 'r') as f:
      filecontents = f.read()
  encoded = base64.b64encode(filecontents)
  python_dict_obj['file'] = encoded
  serialized_json_str = json.dumps(python_dict_obj)
  
  # ... sent to client via socket
  
  # decrpyting
  json_again = json.loads(serialized)
  filecontents_again = base64.b64decode(json_again['file'])
  </code></pre>