def json_safe(string, content_type='application/octet-stream'):
 try:
  string = string.decode('utf-8')
  json.dumps(string)
  return string
 except (ValueError, TypeError):
  return ''.join(['data:', content_type.encode('utf-8'), ';base64,', base64.b64encode(string)]).decode('utf-8')

def json_safe ( string , content_type = 'application/octet-stream' ) : try : string = string . decode ( 'utf-8' ) json . dumps ( string ) return string except ( ValueError , TypeError ) : return '' . join ( [ 'data:' , content_type . encode ( 'utf-8' ) , ';base64,' , base64 . b64encode ( string ) ] ) . decode ( 'utf-8' )
returns json-safe version of string .