Dynamic JSON Formatting Issue - arrays

My application reads JSON data in a particular format. I am pulling data from a database to dynamically create the data. I have the data, I just do not know the proper way to put it all in the following format.
Note: the first 2 sets are pulled from one query, and the "variables" section is what needs to be looped through to populate as the variable names AND values are in their own fields.
Sample Tables<br>
Master Table
ID | Custom_Col1 | Custom_Col2
1 custom_val1 custom_val2
Variables Table
ID | Name | Value
1 var_name1 var_value1
2 var_name2 var_value2
3 var_name3 var_value3
4 var_name4 var_value4
5 var_name5 var_value5
6 var_name6 var_value6
{"Custom_Col1":"custom_val1", "Custom_Col2":"custom_val2","variables":{"var_name1":"var_value1","var_name2":"var_value2","var_name3":"var_value3", "var_name4":"var_value4","var_name5":"var_value5","var_name6":"var_value6"}}
I was able to get the looped values in by using the following, but I just don't know how to get the other variables in. I'm sure it's simple, I've just never worked with JSON before. I've scoured the internet and have found examples, but they have only gotten me so far:
var json = {}
while loop
{
json[name]= value.toString();
}
var stringJson = JSON.stringify(json);

You can create a collection in the same way you did with the var json.
var json = {}
while loopMasterTable
{
json[name]= value.toString();
}
json['variables'] = {}
while loopVariableTable
{
json['variables'][name]= value.toString();
}
var stringJson = JSON.stringify(json);
This will give you the following JSON:
{
"Custom_Col1": "custom_val1",
"Custom_Col2": "custom_val2",
"variables": {
"var_name1": "var_value1",
"var_name2": "var_value2",
"var_name3": "var_value3",
"var_name4": "var_value4",
"var_name5": "var_value5",
"var_name6": "var_value6"
}
}

Related

How to extract specific values from JSON response in Postman and concatenate

I need to be able to do the following in Postman
Parse through a JSON response
Retrieve specific values: some nested, some not
(optional) Concatenate the final result
I can currently perform 1 and I can accomplish 2 for one specific value with the help of this explanation link
What I can't do is retrieve two values. Below is the sample response I am working with
{
"part": "9FH74T00",
"summaries": [
{
"id": "A1AGQF32TR"
}
]
}
I was able to modify the JS from the link above to extract the nested id value
var response = JSON.parse(responseBody);
var ids = response.summaries.map(function(summary) {
return summary.id;
});
console.log(ids);
How can I expand on the JS to also retrieve the part value and ideally output that in the console as part = id or 9FH74T00 = A1AGQF32TR
#lucas-nguyen's seems a valid response/comment to what you propose. What is not well explained is the model. summaries is an array so would you get multiple ids? The fact that you use a map makes me thing there will be multiple ids.
part = id1,id2,id3
or
part = id1
part = id2
part = id3
I've created a sample request with your payload and two ids in summaries. I've console.log 3 approaches:
single part and single id
single part and ids in a list
single part and ids in tuples
So with the example response:
{
"part": "9FH74T00",
"summaries": [
{
"id": "A1AGQF32TR"
},
{
"id": "SECONDID"
}
]
}
You would get the following output:
Option 1:
9FH74T00 = A1AGQF32TR
Option 2, list of ids:
9FH74T00 = A1AGQF32TR,SECONDID
Option 3, list of ids:
9FH74T00 = A1AGQF32TR
9FH74T00 = SECONDID
If for some reason you can't open the example, this is my test tab:
const response = pm.response.json().data;
// Just concatenate single part and single id
console.log("\nOption 1:")
console.log(`${response.part} = ${response.summaries[0].id}`)
// Co
console.log("\nOption 2, list of ids:")
const ids = response.summaries.map( x => x.id)
console.log(`${response.part} = ${ids.join(",")}`)
console.log("\nOption 3, list of ids:")
ids.forEach( x => console.log(`${response.part} = ${x}`))

How to extract data from an API and create an array to send to the another API in Jmeter?

Example:
API A:
{
"customer":[
{
"name":"Jane",
"phone":"9999999",
"email":"jane#test.com"
},
{
"name":"John",
"phone":"8888888",
"email":"john#test.com"
},
{
"name":"Joe",
"phone":"7777777",
"email":"Joe#test.com"
}
]
}
Using the JSON extractor, I want to get the names of all the customers
so: Jane, John, Joe
How do I get these values and turn them into an array
[{"name":"Jane", "name":"John", "name":"Joe"}]
And pass it onto the next API?
Note: That it has to be dynamic so API A could show different 2 names or 1 name or more and needs to be adjusted into the array
First of all your [{"name":"Jane", "name":"John", "name":"Joe"}] is not a valid JSON, you can check it yourself:
so I strongly doubt that this is the string you need to generate.
So if you really need to construct this value you can do something like:
Add JSR223 PostProcessor as a child of the request which returns this "customers" data
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def payload = new StringBuilder()
payload.append('[{')
0.upto(response.customer.size - 1, { index ->
payload.append('"name": "').append(response.customer[index].name).append('"')
if (index != response.customer.size - 1) {
payload.append(',')
}
})
payload.append('}]')
vars.put('payload', payload as String)
Refer the generated value as ${payload} where required
Demo:
More information:
JsonSlurper
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

Comparing multiple values in Google Sheets with App Script for loops

I would like to compare multiple values in a Google Sheet spreadsheet some using for loops in Google App Script. But i would like some advice on the best way to do it.
To explain below...
I have two spreadsheets, A "FOOD" table, and A "FOOD GROUP" table. 
I've written a for loop script that goes through the entire FOOD table.
If the key value of both tables matches, the script will update a column from the FOOD table with a column from the FOOD GROUP table.
The script works without issues. But it can only compare one column between the 2 tables at a time. I would like to modify this script so I can compare multiple columns at once, without having to create a for loop for each specified column.
I pasted my code below. I can also provide images of my spreadsheet if you need it. 
In any case, I'm new to coding, so any constructive feedback or insight to improve my script will be helpful. I'm happy to answer any questions if anything seems unclear.
function FoodGroup_Test() {
var Data = SpreadsheetApp.getActiveSpreadsheet();
var FoodGroupDataSheet = Data.getSheetByName("Food Groups") // "FoodGroup" sheet
var FoodGroupAllValues = FoodGroupDataSheet.getRange(2, 1, FoodGroupDataSheet.getLastRow()-1,FoodGroupDataSheet.getLastColumn()).getValues();
var FoodGroupDataLastRow = FoodGroupDataSheet.getLastRow();
var FoodDataSheet = Data.getSheetByName("Food") // "Food" sheet
var FoodAllValues = FoodDataSheet.getRange(2, 1, FoodDataSheet.getLastRow()-1,FoodDataSheet.getLastColumn()).getValues();
// Object to contain all FoodGroup column values
var Object = {};
for(var FO = FoodGroupAllValues.length-1;FO>=0;FO--) // for each row in the "FoodGroup" sheet...
{
Object[FoodGroupAllValues[FO][15]] = FoodGroupAllValues[FO][11]; // ...store FoodGroup ID Key value
}
for(var F = FoodAllValues.length-1;F>=0;F--) // for each row in the "Food" sheet...
{
var Food_FoodGroupKey = FoodAllValues[F][94]; // Store FoodGroup Key value.
// ...if the Food value dont match, update it with FoodGroup's value
if (Object[Food_FoodGroupKey] != FoodAllValues[F][95])
{
FoodAllValues[F][95] = Object[Food_FoodGroupKey];
}
}
// declare range to place updated values, then set it.
var FoodDestinationRange = FoodDataSheet.getRange(2, 1, FoodAllValues.length, FoodAllValues[0].length);
FoodDestinationRange.setValues(FoodAllValues);
}
FOOD GROUP Table
FOOD table
In order for your code to work as expected, you should do the following changes to your code:
Update your if condition to this one:
Object[Food_FoodGroupKey] != FoodAllValues[F][95] && object2[] != FAllValues[F][86])
In order to avoid the undefined problem use the following line of code:
FoodDataSheet.createTextFinder("undefined").replaceAllWith("");

Send email using google apps script with attachment and mark checkbox as done

I am trying to build a script which will be sending emails based on the data in a spreadsheet in google sheets.
Column 1 - emailAddress
Column 2 - subject
Column 3 - body
Column 4 - signature
Column 5 - fileName (name of the file I'd like to attach, will be different in each case)
Column 6 - checkbox (new functionality in G Sheets, marked= TRUE, unmarked=FALSE).
The aim is to send email only to those which are not marked as sent. After the script is done checkbox should change to TRUE to avoid duplications.
I wrote the below script however there are two issues:
How to make a fileName variable value which will be taken to code from column 5?
How to force the program to change the status of the checkbox to TRUE and to omit those which are already TRUE?
The function:
function Email() {
var rng = SpreadsheetApp.getActiveSheet().getActiveRange()
var sheet = SpreadsheetApp.getActiveSheet();
var data = rng.getValues();
for (i in data)
{
var rowData = data[i];
var checkbox = data[5]
var file = DriveApp.getFilesByName(data[4])
var emailAddress = rowData[0];
var body = rowData[2];
var subject = rowData[1];
var signature = rowData[3];
var message = body + '\n\n'+ signature;
if(checkbox is != 'TRUE')
{
GmailApp.sendEmail(emailAddress,subject,message,
{
attachments: [file.next().getAs(MimeType.PDF)]
}
);
cell.setValue("TRUE");
}
}
}
How to make a fileName variable value which will be taken to code from column 5?
Create a variable var fileName. For uniqueness purposes just add a counter at the end 1,2, etc so it ends looking like fileName1, fileName2, etc
How to force the program to change the status of the checkbox to TRUE and to omit those which are already TRUE?
Use a double for loops because working with sheets is like working with 2D arrays. Inside that create an if statement:
if( getValue() is != 'TRUE'){
cell.setValue("TRUE")
}
Hopefully you got the idea from the pseudocode.

FullCalendar JSON not populating calendar

I think I am missing something. I have set up Full Calendar, and have the default version working, but now am adding my own JSON, and it is not.
Code in the calendar page is
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek'
},
defaultDate: '2017-09-12',
editable: true,
navLinks: true, // can click day/week names to navigate views
eventLimit: true, // allow "more" link when too many events
events: {
url: 'php/get-events.php',
error: function() {
$('#script-warning').show();
}
},
loading: function(bool) {
$('#loading').toggle(bool);
}
});
});
I am learning how to encode JSON as I go along, and I found a tutorial online that gave me some code that seems to work. I have amended the original code in get-events.php to read like this (snippet with DB details taken out)...
// Require our Event class and datetime utilities
require dirname(__FILE__) . '/utils.php';
// Short-circuit if the client did not give us a date range.
if (!isset($_GET['start']) || !isset($_GET['end'])) {
die("Please provide a date range.");
}
// Parse the start/end parameters.
// These are assumed to be ISO8601 strings with no time nor timezone, like "2013-12-29".
// Since no timezone will be present, they will parsed as UTC.
$range_start = parseDateTime($_GET['start']);
$range_end = parseDateTime($_GET['end']);
// Parse the timezone parameter if it is present.
$timezone = null;
if (isset($_GET['timezone'])) {
$timezone = new DateTimeZone($_GET['timezone']);
}
class Emp {
public $id = "";
public $title = "";
public $start = "";
public $url = "";
}
while(!$JAN->atEnd()) {
e = new Emp();
$e->id = $JAN->getColumnVal("ID");
$e->title = $JAN->getColumnVal("TITLE");
$e->start = $JAN->getColumnVal("DATE")."T".$JAN->getColumnVal("TIME");
$e->url = "meeting_info.php?ID=".$JAN->getColumnVal("ID");
echo json_encode($e);
$JAN->moveNext();
}
$JAN->moveFirst(); //return RS to first record
// Read and parse our events JSON file into an array of event data arrays.
$json = file_get_contents(dirname(__FILE__) . '/../json/events.json');
$input_arrays = json_decode($json, true);
// Accumulate an output array of event data arrays.
$output_arrays = array();
foreach ($input_arrays as $array) {
// Convert the input array into a useful Event object
$event = new Event($array, $timezone);
// If the event is in-bounds, add it to the output
if ($event->isWithinDayRange($range_start, $range_end)) {
$output_arrays[] = $event->toArray();
}
}
// Send JSON to the client.
echo json_encode($output_arrays);
When I run the get-events.php page on it's own I get what I am assuming to be a correctly encoded JSON returned, one example in the array is ...
{"id":20,"title":"Executive Committee Meeting","start":"2017-05-01T00:00:00","url":"meeting_info.php?ID=20"}
Can anybody tell me what I have done wrong?
You need to run json_encode() on a complete array of PHP objects, not on each one individually. In your loop, add each Emp to an array, and then encode the array, when the loop ends.
If you look in your browser's network tab at the result of your ajax request, I think you're very likely to see a string of individual objects, but not wrapped in array (square) brackets, and not separated by commas, meaning the JSON is invalid. There's also a good chance there's an error message in your browser's console about the invalid data format. It's best to check this rather than assuming your JSON is correct. There are also online JSON validator tools you can paste it into, to validate the JSON in isolation.
Something like this should work better:
$events = array();
while(!$JAN->atEnd()) {
e = new Emp();
$e->id = $JAN->getColumnVal("ID");
$e->title = $JAN->getColumnVal("TITLE");
$e->start = $JAN->getColumnVal("DATE")."T".$JAN->getColumnVal("TIME");
$e->url = "meeting_info.php?ID=".$JAN->getColumnVal("ID");
$events[] = $e; //add event to the array
$JAN->moveNext();
}
echo json_encode($events); //encode the whole array as a coherent piece of JSON
//P.S. no need to run moveFirst really, since the request is going to end, and discard the resultset anyhow. Depending on your data access technique, you possibly need to close the recordset though, to avoid locking etc.
What you need your code to generate (and what fullCalendar is expecting), is a JSON array - here's a simple example containing 2 elements (representing events):
[
{ "id":20, "title":"Executive Committee Meeting", "start":"2017-05-01T00:00:00", "url":"meeting_info.php?ID=20" },
{ "id":21, "title":"Another Boring Committee Meeting", "start":"2017-05-02T00:00:00", "url":"meeting_info.php?ID=21" }
]
The example code I've given above should generate an array which is in the same format as this JSON sample.

Resources