Sachin Verma
Sachin Verma

Reputation: 3802

JSP conditional expression in javascript

Please take a look at this javascript code inside a GSP(similar to JSP):

var json =JSON.parse("${savedkpiz.get(0).kpi.replace("\"","\\\"")}")

savedkpiz(list object) object is sometimes have no element so access at 0 will throw NPE, how can i prevent this code from executing?? JavaScript if else seems not working

var json =JSON.parse("${if(savedkpiz.size()>0) ? savedkpiz.get(0).kpi.replace("\"","\\\""):""}")

above code too not working?? how can i put condition on this and at the same time if true then populate json variable.

Please help guyz, thanks in advance

Upvotes: 0

Views: 1275

Answers (1)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

You can split your logic and achieve what you want by using JSTL's <c:if> tag and doing the string substitution in JavaScript instead.

var jsonStr = "";

<c:if test="${not empty savedkpiz}">
    jsonStr = "${savedkpiz[0]}".replace(/"/g, "\\\"");
</c:if>

var json = JSON.parse(jsonStr);

Upvotes: 1

Related Questions