views:

38

answers:

1

I am using sun.misc.BASE64Encoder to encode an encrypted value, which is then added to a JSON field and subsequently sent to the client. I use Javascript's eval() function on the client to create an object from the JSON code. When eval() runs, it gives the error:

unterminated string literal

There are other fields in the JSON code, but I've narrowed the error specifically to the base64 encoded field. Here's the offending line of javascript code:

var result = eval( '(' + xhr.responseText + ')' ); 

Here's the JSON object from the Servlet:

{
  'resource':'resource?Signature=j79r/2Hly+HqhS/6fdd+prfsR+kUNijUvDN0QJ14ZR43gzYScOMDypt/crks/CEphTUXVptJvSol
1ZOOvScCUhNOCb7dZk/3MKnI5tOewSACXK32/OJNd8hYpZtSTn+WhA6+f9BUIUZWA83U8Cud/Tb8V
R1yQWbDGG/mM/NiUSiY=', 

'url':'http://somesite.com/pr'
}

I'm not sure why eval is dying, but it seems the value of the 'resource' JSON field contains something it doesn't care for.

Thanks in advance. Tim

+1  A: 

I think it may be because your JSON appears to have line breaks in it. If you remove them, does it work?

alex
This seems like a pretty likely tack. Some Base64 encoders actually put in these line breaks... but because of JavaScript's semicolon insertion, literal linebreaks inside of strings can cause issues. Tim, you might want to check not only what Alex has suggested here but also see if sun.misc.BASE64Encoder has any options to control linebreaks.
Weston C
Just looked at the source of sun.misc.Base64Encoder here: http://www.source-code.biz/base64coder/java/Base64Coder.java.txt . If you're using the `encodeLines` method, you might want to try just using `encode`.
Weston C
Yes, removing the newlines from the encoded string prevents the error. It seems to me a decent Base64 encoder shouldn't output '\n'.
Tim
I think it's for historical reasons -- if I recall correctly, it was invented to feed certain kinds of data through systems that only handled 7 bit character data AND sometimes would wrap lines to various widths. That's rarer nowadays but I think even some webmail systems do it now.
Weston C