Extract data from JSON in Google Sheets

UPDATE: entry.content.$t is actually not the correct field to access individual cells. The proper method is using entry.gsx$[cell column header]. Thank you for pointing out this mistake and assisting in finding a solution.

Initial inquiry:

I am currently attempting to analyze JSON data from a Google Spreadsheet. The issue at hand is that the entries field provides a string representing an entire row of the spreadsheet, but it seems malformed as an object. How have others managed to parse this data? Below is an example of what the content node resembles:

"content":
{
    "type"   :"text",
    "$t"     :"location: 780 Valencia St San Francisco, CA 94110,
               phonenumber: (555) 555-5555,
               website: http://www.780cafe.com,
               latitude: 37.760505,
               longitude: -122.421447"
},

Upon closer inspection, the $t field yields a complete string representing a row in the Google spreadsheet. Therefore, entry.content.$t delivers a string like:

location: 780 Valencia St San Francisco, CA 94110, phonenumber: (555) 555-5555...

Another complicating factor is that certain cells within the spreadsheet contain commas (such as addresses) that are not properly escaped or enclosed in quotes. This means that something similar to

jQuery.parseJSON(entry.content.$t)

or

eval('('+ entry.content.$t + ')')

results in an error. While regex might be an option, I am hopeful that there could be a more refined solution employed by others. Your assistance is greatly appreciated!

Answer №1

The content within the $t attribute is not formatted as JSON. As per the documentation, text nodes are converted into $t attributes, which means the content may not be in a JSON format.

Instead of relying on the structure of the $t attribute, I recommend using a regular expression for parsing. However, please be advised that handling this data may require some advanced techniques. You may need to use assertions since simple methods like splitting on commas will not work. One approach could be searching for patterns like (\w+): to identify elements, and then capturing everything up to the next occurrence of (\w+): without consuming it entirely. It can be achieved with careful manipulation.

Answer №2

Not long ago, I encountered the same issue.

If you need to extract data from $t, you can employ this Regular Expression:

/(\w+): (.+?(?=(?:, \w+:|$)))/mgi

This expression will provide key-value pairs.

Here's a JavaScript snippet to demonstrate:

    var currentPropertiesText = jsonEntry['content']['$t'];

    // var propsArray = currentPropertiesText.split(", ");
    var re = /(\w+): (.+?(?=(?:, \w+:|$)))/mgi;
    var propsArray = re.exec(currentPropertiesText)
    var props = {};

    while (propsArray != null) {

        var propName = propsArray[1];
        var propValue = propsArray[2];

        props[propName] = propValue;

        propsArray = re.exec(currentPropertiesText);
    }

This method should prove beneficial :-)

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

Encountering an "Angularjs 1.2.x Injector:modulerrr" error, even after successfully incorporating ngRoute

I am currently learning angularjs and I have encountered a persistent error. Despite multiple attempts at troubleshooting, I have been unable to resolve it. Here is the code that I have: index.html <!doctype html> <html ng-app="myApp"> <he ...

React's setState is not reflecting the changes made to the reduced array

I am currently working on a custom component that consists of two select lists with buttons to move options from the available list to the selected list. The issue I am facing is that even though the elements are successfully added to the target list, they ...

How to identify the position of an element while scrolling using JavaScript/jQuery

Trying to determine the distance between an element and the top of the window document. After initial value is retrieved during scroll event, it remains unchanged. How can this value be continuously tracked as the page scrolls? JS: $(function() { $(wi ...

Transfer responsibilities of events to the canvas and then fetch the Element in the handler

Currently, I am utilizing the Raphaël library to create a network graph, where nodes are depicted as circles. Users have the ability to dynamically add nodes by clicking on the canvas. When a new node is added, an Element object is pushed into both a Set ...

How can I use XPATH to target a div after choosing a nested element?

I had the task of creating a universal identifier to locate a dropdown menu following a label. There are 10 different forms, each with a unique structure but consistent format, which means I cannot rely on specific IDs or names. Instead, my approach was to ...

Tracking user sessions using cookies, not relying on JavaScript like Google does

Currently, I am working in an environment that utilizes PHP on the server side and Javascript on the client side. In order to monitor user sessions, I regularly send a JS PUT request to the server every 5 seconds. This allows me to gather data such as the ...

The error message "TypeError: Cannot read property 'then' of undefined" is commonly seen in Promises and Express 4.x

[UPDATE] I encountered an issue while attempting to incorporate the promise, resulting in the following error message: TypeError: Cannot read property "then" of undefined getResult(options1).then(function(body){... let options1 = {...}; app.post("/web ...

If I remove my project but still have it saved on my GitHub, do I need to reinstall all the dependencies or can I simply run npm install again?

I have a question regarding my deleted project that is saved on GitHub. If I formatted my PC and lost the project but it's still on GitHub, do I need to reinstall all the dependencies or can I just run 'npm install'? The project has dependen ...

Steps to reveal a div when a button is clicked within a v-for loop using VueJS

Context In my code, I am utilizing a v-for loop to display sets of buttons and corresponding input fields. Each button is supposed to trigger the display of its respective input field upon being clicked. Issue However, the problem arises when the button ...

Error: Unable to access properties of an undefined value (trying to read 'type') within Redux Toolkit

Looking for help with this error message. When trying to push the book object into the state array, I encounter an error. Folder structure https://i.stack.imgur.com/9RbEJ.png Snippet from BookSlice import { createSlice } from "@reduxjs/toolkit" const ...

Ways to quickly terminate a pipeline in a JavaScript transformation

Issue: I am facing a challenge with handling large files (>10GB). At times, I need to process the entire file while other times I only need to sample a few lines. The processing mechanism involves a pipeline: pipeline( inStream, ...

Transforming numerous key-value pairs into JSON formatting: utilizing sed in conjunction with an awk for loop

I am currently working with a data file that has 8 columns delimited by pipes. The last column contains an unpredictable number of key-value pairs, each separated by the equals sign and spaces between each pair. However, the challenge is that the values wi ...

The Flux Router in React Native

I am diving into the world of React Native and currently working on creating a practice app. The issue I'm facing is with the routing functionality in my project. At the moment, I have three main components: the app itself, the router component, and o ...

Tips for avoiding flickering in a background image when it is being changed

Utilizing JavaScript, I am setting a repeated background image from a canvas to a div in the following way: var img_canvas = document.createElement('canvas'); img_canvas.width = 16; img_canvas.height = 16; img_canvas.getContext('2d' ...

Having trouble with the ajax cache not working properly when trying to load an image

I am attempting to dynamically load an image from the server every time a button is clicked using a GET request. However, I am facing an issue where the cached image is being loaded instead of the latest version. Below is the code I am currently using: & ...

Unique Symbols and Characters in JavaScript

My JavaScript code looks like this: confirm("You are selecting to start an Associate who is Pending Red (P RD) status. Is this your intent?") I am encountering a strange issue where I get an alert with special characters, even though my code does not con ...

Information vanishes on mobile devices

After creating a messaging app using React, TypeScript, and Firebase, everything works smoothly locally on both desktop and mobile. However, once the app is deployed, a problem arises specifically on mobile devices. The message input component ("sendMessa ...

I encountered an error of "Unexpected token '>'" while working with an

My code includes an ajax call and utilizes promises in the function: element.on("keypress", ".keyEvents", function(event) { if (event.which == 13) { // create the url and json object var putUrl = ...

Tips on sorting an array within a map function

During the iteration process, I am facing a challenge where I need to modify certain values based on specific conditions. Here is the current loop setup: response.result.forEach(item => { this.tableModel.push( new F ...

The conditional statements within the resize function may not always be triggered when the conditions are fulfilled

Struggling to trigger a function only once when resizing. The issue is that the conditional statements are not consistently executed every time. Here's the code snippet: var old_width = $(window).width(); $(window).on('resize.3col',functio ...