-2

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" class="btn btn-link btn-xs" 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.

jabaa
  • 5,844
  • 3
  • 9
  • 30
Rohan Sharma
  • 1,416
  • 2
  • 14
  • 19
  • I'm not really sure where `)"=""` comes from, but to avoid syntaxError you would need to escape JSON string, please take a look: https://stackoverflow.com/a/2004178/2036169 Or you can JSON.stringify and base64 encode to avoid any formatting issues, of course it only applies if you can decode it in the function. – Rhymond Apr 05 '22 at 11:14
  • Consider providing a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), including the code related to how the server-side string gets rendered client-side. – Iamblichus Apr 05 '22 at 12:51
  • You need to do two things 1. Escape JSON string inside quotes (you can use built-in encodeURIComponent function) 2. Be sure whether you have typed `=` by mistake – ShivCK Apr 05 '22 at 12:56
  • @Rhymondn Did some research. Google app script adds that to all the function calls in its sandbox rendering of javascript. – Rohan Sharma Apr 06 '22 at 10:16
  • @Iamblichus Thanks for the guideline. There is unfortunately nothing else relevant that I can add. Someone who knows app script would have to make test this in their environment. – Rohan Sharma Apr 06 '22 at 10:17

1 Answers1

1

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.

ShivCK
  • 557
  • 10
  • 16