Skip to content

Instantly share code, notes, and snippets.

@dougalcampbell
Created March 12, 2012 19:44
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dougalcampbell/2024272 to your computer and use it in GitHub Desktop.
Handle invalid JS character sequences
/**
* encode to handle invalid UTF
*
* If Chrome tells you "Could not decode a text frame as UTF-8" when you try sending
* data from nodejs, try using these functions to encode/decode your JSON objects.
*
* see discussion here: http://code.google.com/p/v8/issues/detail?id=761#c8
* see also, for browsers that don't have native JSON: https://github.com/douglascrockford/JSON-js
*
* Any time you need to send data between client and server (or vice versa), encode before sending,
* and decode upon receiving. This is useful, for example, if you are using socket.io for real-time
* client/server communication of data fetched from a third-party service like Twitter, which might
* contain Emoji, or other UTF characters outside the BMP.
*/
function strencode( data ) {
return unescape( encodeURIComponent( JSON.stringify( data ) ) );
}
function strdecode( data ) {
return JSON.parse( decodeURIComponent( escape ( data ) ) );
}
@stagas
Copy link

stagas commented May 1, 2012

Fixed my case also, thanks!

@FGRibreau
Copy link

Thanks !

@victusfate
Copy link

Thanks

will be trying this native v8 side later this morning

@mandria
Copy link

mandria commented Mar 29, 2016

thanks it works!!

@nshermione
Copy link

Thanks!!!

@vipickering
Copy link

Works a treat thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment