Daniel
Daniel

Reputation: 6039

Using json inputs in Playframework

So I pass parameters, including one Json one, to one of views:

val json: JsValue = Json.toJson(ResultJson.staticResULT)
Ok(views.html.main("")(StaticContent.initialFormContent, json))

and here is how I receive it in the view:

@import play.api.libs.json.JsValue
@import play.api.libs.json.JsString
@(title: String)(formContent: FormContent, solverResponse: JsValue = JsString(""))

I want to convert solverResponse to json inside the javascript:

var solverLogJson = JSON.parse("@solverResponse.toString()");

when I do this, the browser complains that:

VM11598:1 Uncaught SyntaxError: Unexpected token & in JSON at position 1(…)

Printing the Json it's clear that the quotes " are converted to ". How can I resolve this issue?

Upvotes: 0

Views: 42

Answers (2)

Jamie
Jamie

Reputation: 6124

If it is valid, json, you can use @josephconley's answer, and just cast it as Html.

var solverLogJson = @Html(solverResponse.toString);

Since json is valid javascript, you shouldn't need to parse it again using JSON.parse.

Upvotes: 0

josephpconley
josephpconley

Reputation: 1723

Similar to escaping raw HTML content, you need to wrap the string in an @Html call to pass it correctly to a javascript method, i.e.

var solverLogJson = JSON.parse("@Html(solverResponse.toString())");

This method of passing JSON values via arguments is a bit cludgy, however, I'd suggest creating a separate endpoint that returns JSON and using an ajax call to load the JSON in your javascript.

Upvotes: 1

Related Questions