Java/Javascript/JSON – Passing JSON string from Java into Javascript

I’m passing a JSON string I create in Java as a parameter to a Javascript method called from my servlet. However, when I pass the JSON string, Firebug warns me about the string being passed:

Java code:

String jsonString = "{"id":1,"name":"Joe Smith","data":{"email":"[email protected]","phone":"555-123-4567","title":"CFO","instanceControllerTagLibraryApi":{"developmentMode":false}},"children":[],"instanceControllerTagLibraryApi":{"developmentMode":false}}";

pw.println("<body onload="init('"+jsonString+"');">");


function init(text){

I’ve tried quoting the string during the pass and removing the single quotes. Both basically point to the fact that the string being passed needs to escape the curly braces (somehow).

Error (single quote):

SyntaxError: unterminated string literal [Break On This Error]



The error is not in the JSON string, it’s in the other bit of code.

pw.println("<body onload="init('"+jsonString+"');">"); is really crude attempt to add an onload event.

Don’t try to add the JSON string into the HTML string, it wont work because of the quotes, unless you doubly escape the JSON string, which is just silly.

Currently you output will look like:

<body onload="init('{"id":1, ... }');">
                     ^--- syntax error after this

It will try to execute the JS code init('{.

Leave a Reply

Your email address will not be published. Required fields are marked *