Reputation: 21
I have a server-side controller which is adding an attribute which is a Java object converted to JSON using Jackson:
ObjectMapper mapper = new ObjectMapper();
model.addAttribute("commentObj", mapper.writeValueAsString(commentObject);
My commentObject has a field "comments" which contains quotation marks (") that JSON needs to escape. When I do a simple print-out from the JSP of the commentObject, everything looks good:
[{"commentId":123,"comments": "this \"test\" is here"}]
As you see, the quotes get escaped properly (\").
My problem comes with the javascript on this page that also needs to access this object. So when I run the following:
<script>
var test = ${commentObj};
</script>
If I take a look at the 'test' var, the comments field now reads as follows:
"this "test" is here"
vs.
"this \"test\" is here"
This causes a problem because JSON.parse() will throw an error on 'test' because it is not properly formed JSON anymore.
So my question is, how do I manage to get my commentObj into a javascript object while keeping the escape characters so that I can JSON.parse it properly?
Upvotes: 1
Views: 652
Reputation: 21
Sorry, written at the end of a long day while sick and only just realized now that the 'test' var ends up being a fully formed JS object. So I am able to use that.
That said, I still have the question of how that is happening? It seems to me that it should be coming in as a JSON string that I need to call JSON.parse on. Anyone have an explanation?
Upvotes: 1