Why does one form file iteration work but the other throws % exception? (working with JSON parse in Google-apps-script) - json

I was trying to use the method found here (see most up-voted answer):
Google Apps Script Fastest way to find a row?
I currently use this while it does work I wanted to try the above linked method yet when I replace the below code
function AutoPopulate (evalue)
{
//uses google drive file irretator reads in JSON file and parses it to a Javascript object that we can work with
var iter = DriveApp.getFilesByName("units.json");
// iterate through all the files named units.json
while (iter.hasNext()) {
// define a File object variable and set the Media Tyep
var file = iter.next();
var jsonFile = file.getBlob().getDataAsString();
// log the contents of the file
//Logger.log(jsonFile);
}
var UnitDatabase = JSON.parse(jsonFile);
//Logger.log(UnitDatabase);
//Logger.log(UnitDatabase[1027]);
return UnitDatabase[evalue];
}
WITH THIS CODE:
function AutoPopulate (evalue)
{
//this method did not work for me but should have according to stackflow answer linked above I am trying to understand why or how I can find out why it may have thrown an error
var jsonFile = DriveApp.getFilesByName("units.json").next(),
UnitDatabase = UnitDatabase.getBlob().getDataAsString();
return UnitDatabase[evalue];
}
I get an error in the excecution indicating that there is a % at postion 0 in the JSON, between the methods I dont alter the JSON file in anyway so I dont understand why does the top method work but the bottom one does not?
For further information the idea behind the code is that I have a list of Unit numbers and model numbers that are in a spreadsheet. I then convert this to a JSON file, this however is only done when a new unit is added to the fleet. As I learned one can parse a whole JSON file into a javascript object which makes working with the data set much faster. This javascript object is used so that when a user enters a UNIT# the MODEL# is auto populated based on the JSON file.
I cannot share the JSON file as it contains client information.

Your code does not work for two reasons:
You have a typo in the line UnitDatabase = UnitDatabase.getBlob()... - it should be UnitDatabase = jsonFile.getBlob()...
If you want to retrieve a nested object from a json file - you need to parse the JSOn - otherwise it is considered a string and you can not access the nested structure
Modified working code:
function AutoPopulate2 (evalue)
{
var jsonFile = DriveApp.getFilesByName("units.json").next();
var UnitDatabase = JSON.parse(jsonFile.getBlob().getDataAsString());
return UnitDatabase[evalue];
}
Mind that this code will only work if you have a "units.json" file on your drive and if evalue is a valid 1st-level nested object of this json.

Related

Parse a CSV after a PreProcessor script on JMeter

I'm trying to create a performance test on JMeter where I need to have a variable number of parameters.
This is the CSV file I'm using, so in this case I need 2 variables
inputParameter,var
7,v5
-2,v8
I found that it can be done by using JSR223 PreProcessor so I tried using this script
{
BufferedReader reader = new BufferedReader(new FileReader("path"));
String row = reader.readLine();
String[] header = row.split(",");
row = reader.readLine();
String[] values = row.split(",");
for (int i = 0; i < header.length; i++) {
String name = header[i];
String value = value[i];
sampler.addArgument(name, value);
}
}
This script creates the variables as it should and puts the value of the first row on it. But the problem I have is that I can't find a way to parse a CSV file after the script to change the varibales value.
I tried this
String value = "${"+name+"}";
But it does not get the value of ${imputParameter} that I get from the CSV Data Set Config, it just adds the value %24%7inputParameter%24%7
Is there any way to parse the CSV file after the script runs to modify the value of the variables created by it?
Thanks in advance!
Use vars
String value = vars.get(name);
vars - JMeterVariables - e.g.vars.get("VAR1");
Unfortunately your explanation doesn't make a lot of sense (at least for me), going forward consider:
Providing first 3 rows of your CSV file
Configuration of your CSV Data Set Config
Actual output of the HTTP Request sampler (Request -> Request Body) tab of the View Results Tree listener
Expected output of the HTTP Request sampler
Output of the Debug Sampler (Response Data -> Response Body tab of the View Results Tree listener)

Can you use 'require' in react to import a library?

In my react project, I'm trying to convert XML data from an API call into JSON (using a library called xml-js).
As per the documentation, I'm importing the library in my parent component as follows
const convert = require('xml-js')
and then attempting the convert the API data as follows
const beerList =
'<Product>
<Name>Island Life IPA</Name>
<Volume>300ml/473ml</Volume>
<Price>$10/$13</Price>
<ABV>6.3%</ABV>
<Handpump>No</Handpump>
<Brewery>Eddyline</Brewery>
<IBU/>
<ABV>6.3%</ABV>
<Image>islandlife.png</Image>
<Country>New Zealand</Country>
<Description>Fruited IPA</Description>
<Pouring>Next</Pouring>
<IBU/>
<TapBadge/>
<Comments/>
</Product>'
const beerJs = convert(beerList,{compact: true, spaces: 4})
The errors are telling me that 'convert' is not a function, which tells me that the library isn't being imported. So is the issue with using 'require' syntax, and if so, what alternative would work in react?
which tells me that the library isn't imported
No. If that were the case, you wouldn't even get that far, your require call would throw an error.
Instead, it tells you that convert is not a function - which it isn't! Look at it in a debugger or log it, and you'll see it's an object with several functions inside. You can't call an object like a function.
Take a look at the xml-js docs again:
This library provides 4 functions: js2xml(), json2xml(), xml2js(), and xml2json(). Here are the usages for each one (see more details in the following sections):
var convert = require('xml-js');
result = convert.js2xml(js, options); // to convert javascript object to xml text
result = convert.json2xml(json, options); // to convert json text to xml text
result = convert.xml2js(xml, options); // to convert xml text to javascript object
result = convert.xml2json(xml, options); // to convert xml text to json text
So the solution is to call convert.xml2json and not convert:
const beerJs = convert.xml2json(beerList, {compact: true, spaces: 4})
Or maybe you want an actual object and not a JSON string, then you'd use convert.xml2js (in which case the spaces option is useless):
const beerJs = convert.xml2js(beerList, {compact: true})

How do I parse the JSON returned from Firebase into a Google Sheets row?

the code in Script (FB setup is already done)
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl,secret);
var data = base.getData();
var rowNum = 1;
var range = Sheet.getRange("A"+rowNum+":DH"+rowNum+"");
for (i in data) {
Logger.log(data[i]);
range.setValues(JSON.parse(data[i]))
rowNum += 1;
range = Sheet.getRange("A"+rowNum+":DH"+rowNum+"");
}
the Logger shows the the 112 elements from Firebase just fine, but I can't get the data parsed correctly. the JSON.parse fails saying "Cannot find method setValues(object)".
The message "Cannot find method setValues(object)" is related to range.setValues() method. It means that JSON.parse() works as expected and returns JSON object, but setValues() argument must be 2D array, not JSON object.
You should convert JSON object to array before using as argument. See an example. In general case, the convertion code depends on the object structure, so we can not write the exact code here. It may appear rather long for 112 elements... But we can append it here after you give more details.

Unable to access existing fields in JSON object, keep getting undefined

I have a function in AWS Lambda in which I retrieve an unparsed JSON object, I parse it, and then access its values.
if(data.Payload){
var parsedData = JSON.parse(data.Payload)
console.log("PAYLOAD --> " + parsedData);
console.log("GROUPNAME --> " + parseData.groupName);
...
When I log to the console the parsedData variable, it seems like the parsing was successful:
PAYLOAD --> {"groupName":"Hello!","membersCount":1,"searchField":"hello!"}
The issue arises when I try to access the fields in the JSON as I keep getting undefined:
GROUPNAME --> undefined
NOTE:
If I copy and paste the JSON object
{"groupName":"Hello!","membersCount":1,"searchField":"hello!"}
into a variable on the Chrome debugging console
var parsedData = {"groupName":"Hello!","membersCount":1,"searchField":"hello!"}
I am able to access the properties of the object as I am trying to do in the AWS Lambda function.
parsedData.groupName prints "Hello!"
Edit - temporary solution
The parsedData variable contains a String with a JSON, so the JSON object inside the "" I am not quite sure why. The temporary fix was to double parse the variable but that just seems wrong.
if(data.Payload){
var parsedData = JSON.parse(data.Payload);
var doubleParsed = JSON.parse(parsedData);
if(doubleParsed.groupName !== undefined) {
console.log(doubleParsed.groupName);
}
}
If that is a copy paste of your code, in your 2nd console.log you are using parseData NOT parsedData missing a D.
EDIT Just adding as answer what I wrote in comments.
It seems parsedData was not being parsed correctly, for some reason JSON.parse is not working, I think some information about data.Payload is needed to know what it exactly returns.
Yet the next code seems to solve it, but I would honestly need further explanation as why it needs to be done twice:
var parsedData = JSON.parse(JSON.parse(data.Payload));

trying to convert data from Domino Access Service to a JSON string via JSON.stringify

I want to store the result from a call to a Domino Access Service (DAS) in a localStorage however when I try to convert the result object to a JSON string I get an error.
With DAS you get the result as an Array e.g.:
[
{
"#entryid":"1-CD90722966A36D758025725800726168",
"#noteid":"16B46",
Does anyone know how I get rid of the square brackets or convert the Array quickly to a JSON object?
Here is a snippet of my code:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
localStorage.setItem('myCatalog',JSON.stringify(data));
}
});
Brackets are part of the JSON syntax. They indicate that this is an array of objects. And as you point to a view it is very likely that you would get more than one object back (one for each entry in the view).
So if you are only interested in the first element you could do this:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
var firstRecord = data[0] || {};
localStorage.setItem('myCatalog',JSON.stringify(firstRecord));
}
});
Otherwise, you would need to define a loop to handle each of the objects :-)
/John