Home > Net >  How to pass an object inside a function call of a button in google app script
How to pass an object inside a function call of a button in google app script

Time:04-07

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.

  • Related