How to elegantly replace " with " when passing java string to play framework?


(Yuebin Yang) #1

My task is simple. I have a Java method that returns a string representation of json object. And I try to pass this json string to playframe work.

Suppose that the name of this argument in play is key.
Suppose the String passed by Java method is { “name”:“John”, “age”:30, “city”:“New York”},

In the play framework,
var json_str1= ‘@key’;
var json_str2 = ‘{ “name”:“John”, “age”:30, “city”:“New York”}’;
var parsed_json1 = JSON.parse(json_str1);
var parsed_json2 = JSON.parse(json_str2);

I found that parsed_json2 gotta work but parsed_json1 does not work.
I used google chrome to inspect and find out that all the " in the java string passed in play was replaced with “. So that JSON.parse() does not recognize.
I’ve checked that the java string before passing to play was not replaced with " So the auto work must be done by the play framework.
I found it will work if I do json_str1 = json_str1.replace(’/”/, ‘"’); But this seems not to be the best answer.

Is there a way I can perform the task elegantly ?

(Greg Methvin) #2

It seems like you’re trying to embed a JSON string into a piece of JavaScript within an HTML template.

Twirl uses HTML escaping rules to escape things in an HTML template, which doesn’t make sense inside script elements, since the contents of script elements are always interpreted literally until there’s another </script> tag.

I think what you’re asking to do is not do any escaping and output the raw JSON, as described here, but that’s a bad idea since it leaves you vulnerable to XSS. If the data includes a </script> tag, that would be rendered as is and any arbitrary HTML that came after that, including scripts, will be added to the page.

An alternative is to pass your data as an HTML data attribute, like this:

<div id="root" data-jsondata="@key">

In an HTML data attribute, the HTML escaping makes sense, so the &quot; will get converted into a " when read from JavaScript.

Then in your script:

var json_str1 = document.getElementById("root").dataset.jsondata

I don’t think there’s a much more elegant way to do it than that. I hope that helps.

(Yuebin Yang) #3

Hi greg,

Thank you so much !! You solution works for me case. You are very helpful !