0

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

6
  • You cannot call methods (other than getters) on elements accessed with ${}. Commented Sep 16, 2013 at 12:25
  • Is the first code working? I don't think so, since you are delimiting the strings with double quotes even inside the string itself, making it end and restart more than once. You should escape the double quotes inside the main string or use single quotes(if allowed). Commented Sep 16, 2013 at 12:25
  • @LightStyle first code is working fine!! Commented Sep 16, 2013 at 12:29
  • @SotiriosDelimanolis what else i can do?? Commented Sep 16, 2013 at 12:30
  • @SotiriosDelimanolis where can i learn more about ${} ???? Commented Sep 16, 2013 at 12:31

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

It would be much simpler to just check for ${not empty savedkpiz}.
@user1983983, that is so much better. Thanks for sharing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.