I am having trouble parsing the object correctly. This code is on the backend.
var dummy = { rohan: "sharma" };
var downButton ='<input type="button" value="Download" onclick="downloadFileAutomatically(\'' JSON.stringify(dummy) '\')" />';
On the front end this renders as
<input type="button" value="Download JSON" onclick="downloadFileAutomatically('{" rohan":"sharma"}')"="">
the )"=""
section at the end is random and wrong.
On clicking this button the browser throws Uncaught SyntaxError: Invalid or unexpected token
which is expected behavior.
How should I handle the quotes hierarchy for this to work.
CodePudding user response:
A possible solution
Using string interpolation and encoded JSON string
var dummy = { rohan: "sharma" };
var downButton =`<input type="button" value="Download" onclick="downloadFileAutomatically('${encodeURIComponent(JSON.stringify(dummy))}')"/>`;
Or for clarify
var dummy = { rohan: "sharma" };
var dummyEncoded = encodeURIComponent(JSON.stringify(dummy))
var downButton =`<input type="button" value="Download" onclick="downloadFileAutomatically('${dummyEncoded}')"/>`;
It escapes single and double quotes of JSON data so it can be placed inside quotes. Use decodeURIComponent()
to get orginal JSON string.
However you can escape JSON string by other means too.
Tip: You can use event listeners
instead of onclick
to make code and formatting less error-prone.