How to get specific property from Google Spreadsheet JSON feed - javascript

I am reading JSON from a Google Spreadsheet and need help getting to the text within entry.content.$t. The text is a column named "description" in the spreadsheet. The feed for the spreadsheet is (removed)
So far, my script is
function listChapters(root) {
var feed = root.feed;
var entries = feed.entry || [];
var html = ['<ul>'];
for (var i = 0; i < entries.length; ++i) {
var chlist = entries[i];
var title = (chlist.title.type == 'html') ? chlist.title.$t : escape(chlist.title.$t);
var chapters = chlist.content.$t;
html.push('<li>', chapters, '</li>');
}
html.push('</ul>');
document.getElementById("chapterlist").innerHTML = html.join("");
}
The question is - How do I read "description" from $t to place in the var chapters?

The text within chlist.content.$t is almost, but not quite, properly formatted JSON. Since it's not properly formatted, you cannot use JSON.parse() to create an object that you could then get a description property from.
Here's a brute-force approach that will extract the description, used in place of the original html.push('<li>', chapters, '</li>');:
// Get the text between 'description: ' and 'Chapter website:'
var descStart = chapters.indexOf('description:')+13; //+length of 'description: '
var descEnd = chapters.indexOf('Chapter website:');
var description = chapters.substring(descStart,descEnd);
html.push('<li>', description, '</li>');
Tested with this, checking results in debugger:
function test() {
var url = '---URL---';
var result = UrlFetchApp.fetch(url);
var text = result.getContentText();
var bodytext = Xml.parse(text,true).html.body.getText();
var root = JSON.parse(bodytext);
listChapters(root);
}

Related

Pass var Value to another var For Use With body.replaceText

I'm working on a script that takes my Google Forms data and performs a replace function on a predetermined template Doc file using body.replaceText which is working fine. I've copied a truncated version of that below.
I can submit a form and it will replace the values of the template as designed but there are some multiple-choice (Yes or No) questions that are represented by checkboxes on the template Doc.
I've figured out how to Logger.log the checkboxes via unicode but how do I get var systemOperational.getValue = "yes" to assign a value to var systemOperationalYes using IF/Else?
Trying to have "If systemOperational value is Yes then systemOperationalYes = unicode \u2611 Else systemOperationalYes = unicode \u2610".
Pardon me if any of this sounds amateur. This is literally my first go at this.
//e.values is an array of form values
var timestamp = e.values[0];
var emailAddress = e.values[1];
var jobID = e.values[2];
var storeName = e.values[3];
var systemOperational = e.values[22];
if (systemOperational.getValue = "yes") {
var systemOperationalYes = "\u2611";
Logger.log("\u2611");
} else {
var systemOperationalYes = "\u2610";
Logger.log("\u2610");
}
// Locat template file
var files = DriveApp.getFolderById("XXXXXXX").searchFiles('title contains "'+ jobID +'"');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getId());
}
//file is the template file, and you get it by ID
var templateFile = DriveApp.getFileById(file.getId());
//We can make a copy of the template, name it, and optionally tell it what folder to live in
//file.makeCopy will return a Google Drive file object
var responseFolder = DriveApp.getFolderById("XXXXXXXXX");
//Converts dateSigned var to MM-dd-yyyy for use in file name
var convertedDate = new Date(dateSigned);
Logger.log(convertedDate);
var formatSignDate = Utilities.formatDate(convertedDate, "GMT-5", "MM-dd-yyyy");
Logger.log(formatSignDate);
var folder = responseFolder.createFolder(storeName + '-' + jobID + '-' + formatSignDate);
var copy = templateFile.makeCopy(storeName + '-' + jobID + '-' + formatSignDate, folder);
//Once we've got the new file created, we need to open it as a document by using its ID
var doc = DocumentApp.openById(copy.getId());
//Since everything we need to change is in the body, we need to get that
var body = doc.getBody();
//Then we call all of our replaceText methods
body.replaceText('{{SYSOPY}}', systemOperationalYes);
//Lastly we save and close the document to persist our changes
doc.saveAndClose();
// Convert temporary document to PDF
var pdf = DriveApp.getFileById(copy.getId()).getAs("application/pdf")
var url = DriveApp.getFolderById(folder.getId()).createFile(pdf);
// Delete temp file
//DriveApp.getFileById(templateFile.getId()).setTrashed(true);
}```
try it this way:
var timestamp = e.values[0];
var emailAddress = e.values[1];
var jobID = e.values[2];
var storeName = e.values[3];
var systemOperationalYes;
if (e.values[22] = "yes") {
systemOperationalYes = "\u2611";
Logger.log("\u2611");
} else {
systemOperationalYes = "\u2610";
Logger.log("\u2610");
}

TypeError: Cannot read property '0' of null, fetched URL

I've some issues when I am trying to fetch the data and render in ReactFullpage Component.
The error says: TypeError: Cannot read property '0' of null
Since in the attached script he will get the data from the row here is an example for the var url = https://www.amazon.de/dp/B07YD776RP?ref=myi_title_dp
// script for scraping amazon data outgoing from an url
function import_amazon_data() {
//go to Google Sheet & get new income form column 4
var scraperSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("product_seller_data")
var lrow = scraperSheet.getLastRow();
for(var i=2;i<=lrow;i++){
var url = scraperSheet.getRange(i, 4).getValue()
var regExprice = /<span id="priceblock_ourprice.*<\/span>/gi
var regExsellername = /id=['"]sellerProfileTriggerId['"]>.*?<\/a>/gi
var regEximgsrc = /data-old-hires=".*?"/gi
var getContent = UrlFetchApp.fetch(url).getContentText().trim();
//match of HTML elements with fetched URL
var price = getContent.match(regExprice)
price = price[0]
price = price.replace('<span id="priceblock_ourprice" class="a-size-medium a-color-price priceBlockBuyingPriceString">',"")
.replace('</span>',"")
scraperSheet.getRange(i, 6).setValue(price)
var sellername = getContent.match(regExsellername)
sellername = sellername[0]
sellername = sellername.replace("id='sellerProfileTriggerId'>","")
.replace('id="sellerProfileTriggerId">',"")
.replace('<\/a>',"")
scraperSheet.getRange(i, 7).setValue(sellername)
var imgsrc = getContent.match(regEximgsrc)
imgsrc = imgsrc[0]
imgsrc = imgsrc.replace('data-old-hires="',"")
.replace('"',"")
scraperSheet.getRange(i, 5).setValue(imgsrc)
}
}
Place a check before accessing these arrays: price[0], sellername[0] and imgsrc[0].
To check in development you may use
if(Array.isArray(price) && price.length > 0) {
price = price[0];
} else {
alert('Price array is empty')
}

Parsing JSON within JSON with jQuery

I am using the Twitch API and am attempting to pull follower images. To do this, I have to parse my most recent followers, take the name of these followers and make a request for each to obtain their user image.
$.getJSON(streamFollowers, function(json) {
for (var i = 0; i < 5; i++) {
var followerDisplayName = json.follows[i].user.display_name;
var followerName = json.follows[i].user.name;
var followerJSON = 'https://api.twitch.tv/kraken/channels/' + followerName + '';
$.getJSON(followerJSON, function(json) {
var followerImage = json.logo;
if (followerImage === "null") {
followerImage = "null.jpg";
};
});
What I am having difficulty with is attempting to pull the "followerImage" result from the "followerJSON" parse.
Heres the code in action. http://codepen.io/anon/pen/rxEPXQ
Edit: A second parse isn't required. You can pull user images from the initial parse for usernames etc. I just didn't see see it at the time. My bad.
A users logo is null if a user doesn't have a profile picture set.
http://codepen.io/anon/pen/EPBMox?editors=1011
here it is with all your followers, you can see ones with it set work properly.
var streamFollowers = "https://api.twitch.tv/kraken/channels/tsm_dyrus/follows";
$.getJSON(streamFollowers, function(json) {
for (var i = 0; i < json.follows.length; i++) {
var followerDisplayName = json.follows[i].user.display_name;
var followerName = json.follows[i].user.name;
var followerImage = json.follows[i].user.logo;
$('#followers').append('<li><img src="' + followerImage + '"></img><br />' + followerDisplayName + '</li>');
}
});

firebug TypeError: array element is null

I have a file which contains a list of emails addresses and a CSV file which contains the list of some of the addresses with more information such as names, title etc.
I am trying to compare the two files by check each line of the csv file. If the email in a line of the csv file matches any email in the email list the line is pushed to another array.
I came up with the following code:
function getCsvMatches(){
var holder = [];
var sep = "\n";
var match_holder = "";
var csv = document.getElementById("rawdata2").value;
var csv_array = csv.split('\n');
var email_list = document.getElementById("rawdata1").value;
var emaillist_array = email_list.split('\n');
var csv_length = csv_array.length;
var emaillist_length = email_list.length;
for (var i = 0; i < csv_length; i++){
var email_line = csv_array[i].match(/([a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi)[0];
//alert(email_line) //this works as expected
if(emaillist_array.indexOf(email_line)>= 0){
holder.push(csv_array[i]);
}
}
for (var n = 0; n < holder.length; n++) {
matched_holder += holder[n];
matched_holder += sep;
}
document.extractor3.rawdata3.value = match_holder;
document.extractor3.match_count.value = holder.length;
document.extractor1.emaillist_count.value = emaillist_length;
document.extractor2.csv_count.value = csv_length;
}
Here jsbin link for more code and html: http://jsbin.com/fabumexucu/edit?output
The problem is if I run the script in Firefox I get TypeError: csv_array[i].match(...) is null. But, if alert function is uncommented, I get alert of each emails in the csv file.
Please tell me what I am doing wrong. Thanks.

YouTube API Video Feed Description

Alright, I have been looking off and on for almost a year now (spent all of March trying to do this), and I simply CAN NOT find the code to make this work.
Here's my problem:
I have a code that retrieves my most recent upload for the player on my website (http://weapwn.com). This code only gives me the video, though.
I need code to get the description - not from any one video ID, but from the variable video ID - but all I have is this:
<script type="text/javascript">
function showMyVideos2(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul>'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var content = entry.content.$t;
html.push('<i>', content, '</i>');
}
html.push('</ul>');
document.getElementById('featdesc').innerHTML = html.join('');
}
</script>
Now - replacing "content" does nothing, unless I use "title" (which only retrieves the video title). I must know how to get this damn elusive code to work, because the parameters that Youtube lists are not working!
Am I going about this entirely the wrong way? Or is there simply an error to fix in my code?
Try this:
function showMyVideos2(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = ['<ul>'];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t;
var description = entry.media$group.media$description.$t.replace(/\n/g, '<br/>');
var content = entry.content.$t;
html.push('<i>', content, '</i>','<i>', title, '</i>','<i>', description, '</i>');
}
html.push('</ul>');
document.getElementById('featdesc').innerHTML = html.join('');
}
Hope it helps...

Categories