Is there a way to convert JSON objects for transmission between Google Appscript and its HTML interface?

Google Appscript has the capability to transfer data from server-side scripting to client-side HTML.

E.g.

appscript.gs

var htmlServ = HtmlService.createTemplateFromFile("addDetailsBookingForm");
  let order_id = getSheetOrderID(sheet);   //let order_id = "98";
  htmlServ.order = pullOrderStore(order_id) // let's say this is an array
  const html = htmlServ.evaluate();
  html.setWidth(850).setHeight(450);
  const ui = SpreadsheetApp.getUi();
  ui.showModalDialog(html, "form");

I would like to send JSON through this interface. However, it appears that objects are not supported. Strings and arrays can be sent but not objects.

But, it seems possible to convert a JSON object into a string before sending it, then parse it on the client side to turn it back into an object.

Drawing inspiration from here, I was considering something like

  var htmlServ = HtmlService.createTemplateFromFile("addDetailsBookingForm");
  let order_id = "98";

  orderDetailsObject = pullFromWordPressOrder(order_id)
  htmlServ.orderDetailsObject = JSON.stringify(orderDetailsObject)

  Logger.log(htmlServ.orderDetailsObject)
<etc>

displayjsonfile.html

  <script>
// This will output orderDetailsObject from the server side into orderDetailsObject on the client side. Although they have the same name, they are distinct variables.
     var orderDetailsObject = <?=orderDetailsObject?>; 
     var product_object = JSON.parse(orderDetailsObject);

console.log(product_object)
var order_id = product_object.id //ToTest

An example of JSON data:

{"id":98,"parent_id":0,"status":"pending","currency":"GBP",... (data continues)

The current output of the JSON object in the HTML shows encoding issues with double quotation marks.

Is this behavior expected, or is there a better approach to handling this?

To clarify - while the solution works, it doesn't seem elegant or best practice.

Answer №1

Here's an illustration of how a JSON object can be sent to the client side.

Code.gs

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .getContent();
}

function showTest() {
  var myObject = { name: "MyTest", value: 100 };
  var html = HtmlService.createTemplateFromFile("HTML_Test");
  html.myObject = JSON.stringify(myObject);
  SpreadsheetApp.getUi().showModalDialog(html.evaluate(),"Test");
}

HTML_Test.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <input id="name" type="text">
    <br>
    <input id="value" type="text">
    <script>
      var myObject = <?= myObject ?>;
      (function() {
        myObject = JSON.parse(myObject);
        document.getElementById("name").value = myObject.name;
        document.getElementById("value").value = myObject.value;
      })();
    </script>
  </body>
</html>

Screenshot

https://i.sstatic.net/xeIbO.png

Answer №2

If you encounter issues with passing objects using google.script.run, check out this helpful reference on parameters and return values.

One common issue involves dates. If a date is stored as a string in a cell, retrieve it using getDisplayValues(), pass it as a string, then convert it back to a date object using the new Date() constructor on the server side.

Other than that, most stringifiable objects should work without any problems.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling with HTTP requests in Laravel on iOS?

I'm in need of assistance and would sincerely appreciate any help with the issue I'm facing. I am currently working on an iOS app that communicates with a server running Laravel framework via HTTP requests. //Serialize parameters NSError *error ...

The issue with JSON nested arrays: C# DataContractJsonSerializer fails to return any results

After receiving the following JSON response: {"lastUpdateId":836890951,"bids":[["0.02106900","0.56000000"],["0.02106800","1.38000000"],["0.02106600","3.63600000"],["0.02106500","34.28000000"],["0.02106100","41.49400000"],["0.02105900","1.82500000 ...

PHP parsing JSON

Need assistance with decoding JSON and inserting values into MySQL. Take a look at my code below: $json = ' {"d":[{"Id":1059,"Name":"Alfa Romeo - 145"},{"Id":20020,"Name":"Alfa Romeo - 146"},{"Id":1060,"Name":"Alfa Romeo - 147"},{"Id":20021,"Name":"A ...

Retrieve JSON information via AJAX

Consider the following JavaScript AJAX request: $.ajax({ type: "POST", url: "/myurl", async: false, data: JSON.stringify({}), contentType: "application/json", complete: function (data) { var ...

Incorporate an object property value into an established Angular/Node app by using the syntax " :12 " instead of just " 12 "

My current project is an Angular/Node MEAN stack application, but my primary concern revolves around JavaScript. When I receive a response object, it includes an SQL identity id console.log(response.recordset[0]); The output is "":12 I want to assign t ...

Ways to access the content of the chosen <td> element using Vue?

I have a dynamic table where I retrieve data using $.ajax() from a database. The content in the rows is editable, and I need to save the changes made with vue.js. After updating the content, an $.ajax() function with 4 parameters (name, client_id, url, and ...

Transcribing live content directly from the browser tab

I have a unique idea for developing a browser extension specifically for Chrome. This extension would provide live transcriptions of my team's meetings directly from an open tab in the browser. I am interested in extracting keywords, such as my name, ...

Generate projectiles within a game periodically

I've created a game that features a main character and enemy soldiers who shoot back. I'm facing an issue where only one enemy soldier shoots at intervals, even though I initially used setInterval for both of them. Any suggestions on how to fix t ...

Is it possible for me to replicate this full-screen flash animation using jQuery?

I need some guidance on how to create an animation similar to the one on http://flatuicolors.com without using flash. When you click a color on the website, it triggers a full screen animation with text. I'm not asking for code, just ideas on how to ...

Unusual shift in the modal's behavior occurs when the parent component's style.transform is applied

I have encountered an unusual issue with a modal's appearance and functionality. The modal is designed to enlarge images sent in a chat, with the chat upload preview div serving as the parent element and the modal as the child element. This strange be ...

The function Promise.all typically yields an array with nested arrays

Inside my node Router, the following code snippet is implemented: router.get("/single-base/:id", (req, res) => { Base.find({ _id: req.params.id }) .then(bases => { let basefetches = []; for (let base of bases) { ...

Creating a sticky popup feature for your Chrome extension

Just starting out with chrome extensions and looking to create one that appends an external class to a selected tag. For example, let's say we have the following tag: <h1>extension</h1> When the user clicks on this element, I want to ad ...

The second parameter of the filter function is malfunctioning

I'm currently delving into the "filter" function in AngularJS. Upon reviewing the documentation, I've discovered that it can also take a second parameter. When set to "true", it carries out a strict comparison. HTML <fieldset> <leg ...

Tips for successfully sending a variable through setOnClickListener

Overview: The main layout, map_midvalley_g, contains 8 image buttons that can be clicked. Using a for loop on the data retrieved from the server, the color (green or red) of the image buttons is set. Clicking on any of the image buttons will trigger a popu ...

Using CSS to design a table-like structure with rows that span multiple columns

I am trying to generate a table dynamically using CSS and a JSON array. For example: In the code snippet provided, I have assigned a class of 'spannedrow' to span certain cells in the table, although the class is not defined yet. This is just ...

Exploring the capabilities of nested WebGL render targets in the three.js library

I am currently developing an application for the Oculus Rift using JavaScript, three.js, and OculusRiftEffect.js. In order to create a transparent portion of a 2D ring for the menu, I am attempting to generate a MeshBasicMaterial.alphaMap texture on a Web ...

Use CodeMirror on an existing div element

My div named "content_editable" is the center of my code editing application. I need it to adhere to specific CSS dimensions, but I also want to integrate CodeMirror syntax highlighting into it. However, following the documentation's instructions does ...

Sequelize makes it easy to input records into various tables simultaneously

Embarking on my first experience with Sequelize and MySQL, I am seeking guidance on inserting data into two tables with a foreign key relationship. Let's delve into the structure of the entities - bookingDescription and bookingSummary. //bookingSumma ...

Client connected via Socket.io is not receiving the message event

My project was built using express-generator as the skeleton, so I had to implement a workaround which I found here. SERVER: io.on('connection', function(socket){ socket.on('message', function(msg){ io.emit('message', msg) ...

Restore original scale ratio to 1:1 following zoom

I am looking for a way to revert the image back to its original zoom level when a button is clicked using the onclick() event. I require the specific code for the onclick() event function. This is the div element in my HTML: div id="zoom"> ...