Input validation is essential to prevent untrusted input of getting executed, the use of encoding libraries available can assist on enforcing strict input control.
Encoding Libraries:
Prevention:
DOM based XSS Prevention Cheat Sheet
Handling Untrusted JSON safely