Transform JSON data into a Google Sheet using Google Apps Script

Having trouble inserting the JSON response into Google Sheet using Google Apps Script with the code below. Running into errors, even though I can't seem to pinpoint the issue.

Take a look at the screenshot and code snippet provided:

    function myFunction() {

  var key_67 = 'YYYYYYYYYYYYYYYYYY';
  var ss_67 = SpreadsheetApp.openById(key_67);
  var sheet_67 = ss_67.getActiveSheet();
  sheet_67.getRange('A1:AZ10000').clearContent();
 var url = 'https://creator.zoho.com/api/json/arfater/view/Leads_Report?authtoken=XXXXXXXXXXXXXXXXXXXX&scope=creatorapi&zc_ownername=ipekuet';
 var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);



  var stats=[]; //create empty array to hold data points



  //The following lines push the parsed json into empty stats array

    stats.push(data.Yearly_Sales); //temp
    stats.push(data.Email); //dewPoint
    stats.push(data.Phone); //visibility

  //append the stats array to the active sheet 
  sheet_67.appendRow(stats)

}

https://i.stack.imgur.com/2mSnE.png

Answer №1

After analyzing the JSON response from the Postman app, it appears as follows:

var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f7b6a7c7b4f75606760216c6062">[email protected]</a>","Phone":"123-032-03323","P‌otentially":50,"Stat‌e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]};

Upon attempting to use this response directly, an error is encountered:

function JsonResponse(){
 var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="780c1d0b0c3802171017561b1715">[email protected]</a>","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
 var data = JSON.parse(json);
Logger.log(data); 
}

The error message received is:

SyntaxError: Unexpected token: v

This suggests that the API response includes the term var zohoipekuetview65, which seems to be causing the issue (likely a bug).

To extract just the JSON response from the string, you can utilize the following code snippet:

function trialParse(){
var json ='var zohoipekuetview65 = {"Leads":[{"Yearly_Sales":"$ 1,000.00","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0470617770447e6b6c6b2a676b69">[email protected]</a>","Phone":"123-032-03323","P‌​otentially":50,"Stat‌​e":"NY","ZipCode":"1‌​0036","Street":"1515 Broadway","Country":"USA","ID":"2198633000000063029","City":‌​"New York","Name":"Arfater Rahman"}]} '
Logger.log(JsonResponse(json))
}
function JsonResponse(response){
  Logger.log(response)
  var json = response.split("=")[1]
  var data = JSON.parse(json);
  Logger.log(data);
  return data  
}

You can then simply call the function in your code using var data = JsonResponse(json).

Lastly, consider utilizing Logger.log(json) as suggested by Jordan Rhea to output the API response to your logs. You can view these logs under Views > Logs.

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

What is the best way to preserve the state of child components after being filtered by the parent component?

I've been working on a small application using create react app to enhance my skills in React, but I've hit a roadblock with managing the state. The application maps through JSON data in the parent component and displays 6 "image cards" as child ...

How can I incorporate fetch into my code using VSCode?

I am completely new to using JS. I want to incorporate fetch in VSCode, but I'm having trouble importing it. When I try: import fetch from "node-fetch"; I get this error: (node:19856) Warning: To load an ES module, set "type": &q ...

Getting Values from .Properties File in JavaScript/HTML pages that are Executing in a Node.js Server

I have a configuration file named "site.properties" with the following content: #Properties file #Database Connection Info db.host.name = localhost db.user.name = username db.password = password db.database.schema = db1 #Server Connection Info ...

Guidelines for submitting and displaying content on a single page with jQuery and MySQL

Objective: To develop a Q&A Script using PHP, JavaScript, and jQuery that allows users to post questions and provide answers. Upon submitting a new answer, it should be stored in the database and automatically displayed in the answers section. Challenge: ...

Determine the duration/length of an audio file that has been uploaded to a React application

I am working on a React web application built with create-react-app that allows users to upload songs using react-hook-forms. The uploaded songs are then sent to my Node/Express server via axios. I want to implement a feature that calculates the length of ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

Using JSON to selectively serialize object properties

I have a specific object named MyObject with various properties. By using a Linq query, I populate MyList with instances of MyObject before serializing it into JSON format. As a result, I get something like this: List<MyObject> MyList = new List< ...

Tips for turning on a gaming controller before using it

Current Situation In my ionic side menu app, I have a main controller called 'main view'. Each tab in the app has its own controller, which is a child of the main controller. The issue I'm facing is that when I start the app, the first cont ...

Converting JSON market data to a pandas dataframe using Python with marketstack

I'm having trouble converting the marketstack API's 'intraday' output from JSON to a pd dataframe. Here's the error I'm encountering: data = r.json()['intraday'] KeyError: 'intraday' This is the Python cod ...

An error occurs when using e.slice function

I am facing an issue with my kendoDropDownList that uses kendo UI and jQuery. I cannot figure out why this error is occurring. $("#drpState").kendoDropDownList({ optionLabel: "States...", delay: 10, ...

showcasing a map on an HTML webpage

Seeking advice on integrating a map feature in HTML to mark store locations. Working on an app for a business community and need help with this specific functionality. Your assistance would be greatly appreciated! ...

Encounter the "Error: Source 'cloudsTileLayer-RasterSource' not found" message while trying to integrate a weather tile layer into Azure Maps

I have been working on a React application that utilizes the React-Azure-Maps npm package. My current challenge involves creating a weather layer, which I believe shares similarities with the sample code provided for layers. The code snippet responsible f ...

Understanding JSON in R by extracting keys and values

I have a JSON URL that I need to parse in R. The URL is https://{{API_HOST}}/api/dd/new and contains both keys and values. I can easily parse this JSON in Postman by using the keys and values in the Headers section. Now, I am looking for a way to achieve t ...

Is it possible to transform an arrow function into a regular function?

Currently, I am working my way through the AJAX type ahead course in Javascript 30 by Wes Bos. As I progress through this course, I have made a conscious effort to minimize my use of ES6 features for the sake of honing my skills. If you want to see the fi ...

While utilizing deep scan selector in C#, Json.NET successfully removes properties, but the same operation results in an ObjectNullReferenceException when implemented in F

When using json.net 12.0.3 in a netcoreapp3.1 application, I have encountered an issue where the code functions correctly when written in C#, and also works using dot notation in F#. However, when attempting to remove an element found by a deep scan select ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

What is preventing the data property from updating in setInterval?

Looking for a way to increase the speed of the props while my marker is moving? Currently, the speed only updates when the pause button is clicked. How can I automatically update this.speed when clicking the speed button? I have defined the speed prop in ...

Utilizing nested JSON in Microsoft SQL Server

My table consists of USER_DATA (user data table) with 2 rows (essentially 2 entries). I crafted a nested JSON query like so -> SELECT CONCAT( first_name,' ', last_name) AS displayName, first_name AS givenName, last_name AS surname, ...

Utilizing Firebase objects across multiple files: A comprehensive guide

I apologize for my ignorance, but as I am teaching myself, I have not been able to find the answer in the available documentation. My current project involves developing a Vue application with Firebase as the backend. To utilize Firebase services, you mus ...

AngularJS: How to accurately retrieve the offsetTop value upon page initialization

Issue: I am facing difficulty in obtaining the accurate top offset value of a DOM element immediately after the page has loaded. In the project I am currently working on, it is essential to retrieve the offsetTop value of various DOM elements as soon as ...