I use Zapier to automate many of our business functions, which is great, but I got stuck trying to count the number of arrays or, if you like, a particular word pattern that comes from a string. I can tidy up the string with Zapier formatter, but cannot figure out how to carry out a count.
Here is an example of a tidied string where " have been removed:
[{Name:Jon,Surname:Smith},{Name:David,Surname:Michael},{Name:Sam,Surname:Fields},{Name:Katy,Surname:Milnes}]
In this instance I would want the count on say "Name" to return 4.
I have looked at different code examples for counting words but cannot execute them correctly in the code action of Zapier. This is probably really straight forward but I do not come from a coding background so a simple Java (or Python) script to drop into the Zapier code action or some pointers on how to solve this would be greatly appreciated.
Thanks
What are you really trying to achieve by trying to count the word?
Do you just want to know the number of objects the array contains? If that is the case something like this would work. Assuming that the array is in your inputData for the code step.
var data = JSON.stringify([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}]);
var inputData = {objArr: data};
// Do not insert the above lines in your code step.
// Set the objArr to your array in the inputData step.
var parsedObjArr = JSON.parse(inputData.objArr);
// Skip the above step if the array is not in the inputData object.
var arrLen = parsedObjArr.length
console.log('Array Length: ', arrLen);
// The line below outputs data from the code step.
output = {arrLen}
Also note, you do not need to remove the quotes from the JSON string.
If the array is not in the inputData of the code step, you can just directly use the length method on the array.
Well in Python you can convert the json string into dictionary with key as the name. Length of dictionary is what you are looking for. Here is the example:
import json
from collections import defaultdict
d=defaultdict(list)
x=json.dumps([{'Name':'Jon', 'Surname':'Smith'},{'Name':'David','Surname':'Michael'},{'Name':'Sam','Surname':'Fields'},{'Name':'Katy','Surname':'Milnes'}])
json_string=json.loads(x)
for obj in json_string:
if(obj['Name'] in d):
d[obj['Name']].append([obj['Name']+' '+obj['Surname']])
else:
d[obj['Name']]=[obj['Name']+' '+obj['Surname']]
print(len(d))
Related
I would like to substract json entries from the main JSON bulk data, based on an input, in JavaScript. Each entry in the main JSON data has it's own unique ID, but the filter should be based on the text identifier rather than the ID. I would like to retrieve for example all entries that contain the word burg (Burg, BURG, bUrg, etc.) or any other given variety. This should of course also work with other search terms. I do not possess the JavaScript skills to do this.
In the data given below this should return 3 results. Obviously, the result should be the exact same JSON format.
Example JSON:
{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}
Do not use JavaScript for this. Use SQL and its LIKE operator instead.
But if you insist on using JavaScript for this…
Just like HTML, regular expressions cannot fully parse JSON because of serialization.
Filtering after JSON.parse is quite easy however; you can use the Array.prototype.filter() method:
var s = '{"type":"FeatureCollection","features":[{"id":1,"text":"Cape Town"},{"id":2,"text":"Kimberley"},{"id":3,"text":"Beaufort West"},{"id":4,"text":"Johannesburg Park"},{"id":5,"text":"Germiston"},{"id":6,"text":"Pietermaritzburg"},{"id":7,"text":"Durban"},{"id":8,"text":"Bellville"},{"id":9,"text":"Wellington"},{"id":10,"text":"Huguenot"},{"id":11,"text":"Worcester"},{"id":12,"text":"Matjiesfontein"},{"id":13,"text":"Laingsburg"},{"id":14,"text":"Prince Albert"},{"id":15,"text":"Hutchinson"},{"id":16,"text":"De Aar"},{"id":17,"text":"Warrenton"}]}';
var input = "burg";
var o = JSON.parse(s);
o.features = o.features.filter(e => RegExp(input, 'i').test(e.text));
console.log(JSON.stringify(o));
I'm trying to generate a google form that has a few hundred options in a drop down.
I have all the name values in a single cell formatted as follows:
'user1','user2','user3'
It is set as in the code as follows:
var studentNames = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
When I use this variable as shown below it treats it all as a singe value instead of an array.
.setChoiceValues([studentNames])
Any help in where to go from here?
is it a string of words with single quotes and a comma to separate them? if so, you can just do a split on the comma
var s = data
var arr = s.split(",");
and now you will have an array of strings. not sure if this answers your question.
Thanks everyone for getting me pointed in the right direction.
Turns out split was just part of the answer, I had to turn it into a string first.
.toString().split(",");
getValues() returns an object, so you need to interact with it to get the string of values for your array.
Given you are selecting just one cell and so don't need to iterate through the object, try something like this:
var studentNamesObj = SpreadsheetApp.openById('REDACTED').getSheetByName('Student List').getRange(3,3).getValues();
var studentNames = studentNamesObj[0][0].split(",");
I'm creating a simple flashcard generator and have a JSON String containing multiple arrays and objects that looks like this:
data = [{"front":"What is your name?","back":"Billy"},{"front":"How old are you?","back":"40"}][{"front":"Is this a test?","back":"yes"}]
When I console.log(data.length) i get 130.
I can enter more than one flashcard at a time, and can enter the flashcards at any given time. That's why there's the ][ are in the middle of it.
I'm trying to loop through said array and end up with something along the lines of:
data = [{"front":"What is your name?","back":"Billy"},{"front":"How old are you?","back":"40"},{"front":"Is this a test?","back":"yes"}]
Where console.log(data.length) = 3
And eventually data[i].front = "What is your name?"
Can someone please put me in the right direction? The data is being read from a txt file if that makes a difference.
Ok, if you are not controlling "json" creation, and can't get valid JSON, then just try to fix it.
const fixedData = data.replace('][', ',');
const parsedData = JSON.parse(fixedData);
console.log(parsedData.length); // 3
If you can control input, just construct valid JSON. Ask different question if don't know how.
In my getOptions.jsp file, I have created a string with jstl.
<c:set var="options" value="Maximize,Redo,RemoveFormat,Save" />
This string should now be transformed into this format (which is, if I am correct, a multidimensional javascript array (or is it json?)).
[['Maximize', 'Redo','RemoveFormat','Save']]
I have to do this because this format is expected by a javascript method located in another .jsp (showToolbar.jsp),
function handleToolbar(options) {
//toolbar = [['Maximize', 'Redo','RemoveFormat','Save']]; the expected format!
toolbar = options;
}
So my question is, how do I transform the comma-seperated string 'options' into the format that is expected in the 'toolbar' variable in order to pass it from one jsp to the other and pass it as a parameter of the handleToolbar function.
Note: I guess it is not ideal to use javascript in a jsp but that I cannot change because I inherited the code.
Thanks alot in advance, I've been searching for hours for the solution and can't find it.
Simple:
var myString = "Maximize,Redo,RemoveFormat,Save";
var myArray = [myString.split(',')];
The result is an array that has 1 element in it. That 1 element is this array:
['Maximize', 'Redo','RemoveFormat','Save']
So, myArray is:
[['Maximize', 'Redo','RemoveFormat','Save']]
db = new Array("myserver", "myfolder\\mydb.nsf")
dir = getComponent("Dir").value;
div = getComponent("Div").value;
lu = #DbLookup(db, "ManagerAccess", dir + "PP" + div, "DTManagers");
var a = [];
a.push(lu);
var item:NotesItem = docBackEnd.replaceItemValue('FormReaders', #Unique(a));
item.setReaders(true);
That code is on the querySaveDocument ssjs. The result I get from the #DbLookup (when I put in a computed field) look like this:
Pedro Martinez,Manny Ramirez,David Ortiz,Terry Francona
I tried doing an #Explode(#Implode) thing on it, but it doesn't seem to work.
The error I get in the browser just tells me that the replaceItemValue line is broken.
To test it, I pushed several strings one at a time, and it worked correctly populating my FormReaders field with the multiple entries.
What am I doing wrong?
I see several problems here:
A. In cases as described by you #Dblookup in fact would return an array. If you push an array into a plain computedField control it will exactly look as that you wrote:
value1, value2, ..., valueN
A computedField doesn't know anything about multiple values etc, it just can display strings, or data that can be converted to strings.
If you want to test the return value you could try to return something like lu[0]; you then should receive the array's 1st element, or a runtime error, if lu is NOT an array. Or you could ask for the array's size using lu.length. That returns the number of array elements, or the number of characters if it's just a plain string.
B. your code contains these two lines:
var a = [];
a.push(lu);
By that you create an empty array, then push lu[] to the first element of a[]. The result is something like this:
a[0] = [value1, value2, ..., valueN],
i.e. a is an array where the first element contains another array. Since you don't want that, just use #Unique(lu) in your replaceItemValue-method.
C. I don't see why replaceItemValue would throw an error here, apart from what I wrote in topic B. Give it a try by writing lu directly to the item (first without #Unique). That should work.
D. for completeness: in the first line you used "new Array". A much better way to define your db parameters is
var db = ["myserver", "myfolder/mydb.nsf"];
(see Tim Tripcony's comment in your recent question, or see his blog entry at http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-9AN5ZK)