have a nice day everyone, i want to ask something, i need to make JSON array using square bracket instead of curly breacket, but now i've JSON like this:
{
noTransaksi: "202006041323372",
nopolTransaksi: "B11",
nominalTransaksi: "1.000",
masukTransaksi: "04 June 2020 13:23:37",
keluarTransaksi: "04 June 2020 14:26:25",
lokasiTransaksi: "Jakarta",
nipKaryawan: "002002",
shiftTransaksi: "1"
},
{
noTransaksi: "202006040703302",
nopolTransaksi: "B2213",
nominalTransaksi: "0",
masukTransaksi: "04 June 2020 07:03:30",
keluarTransaksi: "04 June 2020 14:25:42",
lokasiTransaksi: "Jakarta",
nipKaryawan: "002007",
shiftTransaksi: "1"
},//...
i want to change it to something like this:
[
noTransaksi: "202006041323372",
nopolTransaksi: "3752",
nominalTransaksi: "1.000",
masukTransaksi: "04 June 2020 13:23:37",
keluarTransaksi: "04 June 2020 14:26:25",
lokasiTransaksi: "RSUDTA",
nipKaryawan: "002002",
shiftTransaksi: "1"
],
[
noTransaksi: "202006040703302",
nopolTransaksi: "AG1592",
nominalTransaksi: "0",
masukTransaksi: "04 June 2020 07:03:30",
keluarTransaksi: "04 June 2020 14:25:42",
lokasiTransaksi: "RSUDTA",
nipKaryawan: "002007",
shiftTransaksi: "1"
],//....
so i can fit the JSON to my datatable, because it need square bracket instead of curly bracket, anyway i'm using reactjs too, it is possible to make JSON array like that?
oh ya, this is my code
if(mysqli_num_rows($result) > 0){
$emparray = array();
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = array(
'noTransaksi'=>$row['noTransaksi'],
'nopolTransaksi'=>strtoupper($row['nopolTransaksi']),
'nominalTransaksi'=>number_format($row['nominalTransaksi'],0,",","."),
'masukTransaksi'=>date("d F Y H:i:s", strtotime($row['masukTransaksi'])),
'keluarTransaksi'=>date("d F Y H:i:s", strtotime($row['keluarTransaksi'])),
'lokasiTransaksi'=>strtoupper($row['lokasiTransaksi']),
'nipKaryawan'=>strtoupper($row['nipKaryawan']),
'shiftTransaksi'=>$row['shiftTransaksi'],
);
}
$no++;
}
echo json_encode($emparray);
}
mysqli_close($con);
i really appriciate if somebody can help me:)
The square brackets produce a list/array.
The curly brackets produce an object with key/value pairs.
The list can then be a value of a key/value pair.
you cant just change it u can use [] inside the {} brackets
Related
I am new to GAS with a little knowledge in Javascript
I am trying to read a list of IDs (column A in 'Outbound' sheet) and paste IDs to new 'temp' sheet (col A) and only show ID once if ID is duplicated, This part of my code is working fine.
Next I want to copy the rows of data over from 'Outbound' sheet to the new 'temp' sheet if ID match, but if a ID is duplicated then it will merge columns E:K.
I haven't got to the merging part as my code is not working when looking through the IDs and pasting the relevant rows across.
Link to Google Sheet and script: Click Here
This is my code so far, I appreciate some variables/lines of codes are not used as I have been playing around with my code and there may be ways to speed things up.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var newdata = new Array();
var data = ss.getDataRange().getValues(); // get all data
var destSheet = ss.getSheetByName("temp");
var lastRow = sheet.getLastRow();
var lastCol = sheet.getLastColumn();
function main(){
var data = findUnique();
sort();
copyRowData();
}
function findUnique(){
for(nn in data){
var duplicate = false;
for(j in newdata){
if(data[nn][col] == newdata[j][0]){
duplicate = true;
}
}
if(!duplicate){
newdata.push([data[nn][col]]);
}
}
//Logger.log(newdata);
}
function sort(){
newdata.sort(function(x,y){
var xp = Number(x[0]); // ensure you get numbers
var yp = Number(y[0]);
return xp == yp ? 0 : xp < yp ? -1 : 1; // sort on numeric ascending
});
//Logger.log(newdata);
destSheet.clear();
destSheet.getRange(1,1,newdata.length,newdata[0].length).setValues(newdata); // Paste unique HS ID to new tab
}
function copyRowData() {
//var sheet = ss.getSheetByName('Outbound'); //source sheet
var range = sheet.getRange(2,1,lastRow,5).getValues();
Logger.log(range);
var destlastRow = destSheet.getLastRow();
var criteria = destSheet.getRange(1,1,destlastRow).getValues();
Logger.log(criteria);
var data1 = [];
var j =[];
Logger.log(range.length);
//Condition to check in A:A, if true, copy the same row to data array
for (i=0;i<range.length;i++) {
for (j=0; j<criteria.length; j++){
if (range[i] == criteria[j]) {
data1.push(range[i]);
}
}
}
Logger.log(data1.length);
//Copy data array to destination sheet
destSheet.getRange(2,2,data1.length).setValues(data1);
//targetrange.setValues(data1)
}
I am looking for an output similar to this, where Shaun and Kennedy have merged data in cells E to K:
Click for image of expected outcome
Any help is much appreciated.
Modified Script
I approached this a bit differently from your script.
function main() {
let file = SpreadsheetApp.getActive();
let sourceSheet = file.getSheetByName("Outbound");
let sourceRange = sourceSheet.getDataRange();
let sourceValues = sourceRange.getValues();
// Removing header row into its own variable
let headers = sourceValues.shift();
//==========================================
// PHASE 1 - dealing with duplicates
// Initializing the duplicate checking object
// Using the ID as the key, objects will not
// allow duplicate keys.
let data = {}
// For each row in the source
// create another object with a key for each header
// for each key assign an array with the values
sourceValues.forEach(row => {
let rowId = row[0]
// If the id has already been added
if (rowId in data) {
// add the data to the array for each header
headers.forEach((header, index) => {
data[rowId][header].push(row[index]);
})
} else {
// create a new object with an array for each header
// initialize the array with one item
// the value of the cell
let entry = {}
headers.forEach((header, index) => {
entry[header] = [row[index]];
})
data[rowId] = entry
}
})
// PHASE 2 - creating the output
let output = []
// You don't want the name to be merged
// so put the indices of the columns that need to be merged here
let indicesToMerge = [4,5,6,7,9,10]
// For each unique id
for (let id in data) {
// create a row
let newRow = []
// temporary variable of id's content
let entry = data[id]
// for each header
headers.forEach((header, index) => {
// If this field should be merged
if (indicesToMerge.includes(index)) {
// joing all the values with a new line
let content = entry[header].join("\n")
// add to the new row
newRow.push(content)
} else {
// if should not be merged
// take the first value and add to new row
newRow.push(entry[header][0])
}
})
// add the newly constructed row to the output
output.push(newRow)
}
//==========================================
// update the target sheet with the output
let targetSheet = file.getSheetByName("temp");
let targetRange = targetSheet.getRange(
2,1,output.length, output[0].length
)
targetRange.setValues(output)
}
Which outputs this on the temp sheet:
How the script works
This script uses an object to store the data, here would be an example entry after the first phase of the script is done:
'87817':
{
ID: [87817, 87817, 87817],
Name: ["Kennedy", "Kennedy", "Kennedy"],
Surname: ["FFF", "FFF", "FFF"],
Shift: ["NIGHTS", "NIGHTS", "NIGHTS"],
"Area Manager completing initial conversation": ["AM1", "AM1", "AM1"],
"WC Date ": [
Sun Nov 29 2020 19:00:00 GMT-0500 (Eastern Standard Time),
Sun Feb 14 2021 19:00:00 GMT-0500 (Eastern Standard Time),
Sun Mar 07 2021 19:00:00 GMT-0500 (Eastern Standard Time),
],
"Score ": [0.833, 0.821, 0.835],
Comments: ["Comment 6", "Comment 10", "Comment 13"],
"Intial Conversation date": ["Continue to monitor - no action", "", ""],
"Stage 1 Meeting Date": [
"N/A",
Fri Feb 19 2021 19:00:00 GMT-0500 (Eastern Standard Time),
Mon Mar 29 2021 19:00:00 GMT-0400 (Eastern Daylight Time),
],
"Stage 1 Outcome": ["", "Go to Stage 1", "Stage 2"],
};
As you can see, if it finds a duplicate ID, for the first pass, it just copies all the information, including the name and surname etc.
The next phase involves going through each of these entries and merging the headers that need to be merged
by concatenating the results with a newline \n, resulting in a row like this:
[
87817,
"Kennedy",
"FFF",
"NIGHTS",
"AM1\nAM1\nAM1",
"Sun Nov 29 2020 19:00:00 GMT-0500 (Eastern Standard Time)\nSun Feb 14 2021 19:00:00 GMT-0500 (Eastern Standard Time)\nSun Mar 07 2021 19:00:00 GMT-0500 (Eastern Standard Time)",
"0.833\n0.821\n0.835",
"Comment 6\nComment 10\nComment 13",
"Continue to monitor - no action",
"N/A\nFri Feb 19 2021 19:00:00 GMT-0500 (Eastern Standard Time)\nMon Mar 29 2021 19:00:00 GMT-0400 (Eastern Daylight Time)",
"\nGo to Stage 1\nStage 2",
]
Comments
I believe the main difference between this script and yours is that it does everything in memory. That is, it gets all the data, and then never calls getRange or getValues again. Only at the end does it use getRange just for the purposes of outputting to the sheet.
The other difference appears to be that this one uses the inbuilt property of objects to identify duplicates. I.e. an object key cannot be duplicated inside an object.
Perhaps also, this approach takes two passes at the data, because the overhead is minimal and otherwise the code just gets hard to follow.
Merging data like this can get endless as there are many tweaks and checks that can be implemented, but this is a working bare-bones solution that can get you started.
When I tried to convert 2020-12-14 to 14 Dec 2020 by using
1st Method
<small>{item.date}</small>
2nd Method
{new Date(item.date).toLocaleString()}
then I got below output
2020-12-14
12/14/2020, 5:30:00 AM
Is there any way to convert the date format from 2020-12-14 to 14 Dec 2020.? in reactjs
A small modification to this elegant answer by Dave splits the toString date string into an array and formats it into the result you want. Check the code below:
const date = new Date(2020, 11, 14).toString().split(" ");
// ["Mon", "Dec", "14", "2020", "14:05:53", "GMT+0100", "(Central", "European", "Standard", "Time)"]
console.log(date[2] + " " + date[1] + " " + date[3]);
// 14 Dec 2020
using moment package
moment(moment('2020-11-18', 'YYYY-MM-DD')).format('DD MMM YYYY');
A chrome based APP which I am supporting gives us this error.
I tried to find out more about the error but was unsuccessful.
Can someone kindly explain me on what could be the cause of this.
The Error is as below Image
The put is happening at this snippet
var ydbRequest = ydbStorage.put(dbName, data);
The dbName: OUTLETS
and the data value is:
1. Action: "Submit"
2. ChannelGroup: "ZC03"
3. City: "LA"
4. CreateDate: Fri Jun 24 2016 10:23:03 GMT-0400 (Eastern Daylight Time)
5. MUValue: Object
6. ModifiedDate: Mon Jun 27 2016 11:16:24 GMT-0400 (Eastern Daylight Time)
7. Mu: "U39 "
8. Name: "54321"
9. OutletId: "0000054321"
10. OutletImage: ""
11. Promotion: Object
12. SignatureImage: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAABLCAYAAABeMdGUAAAFTElEQVR4Xu3azcttUxwH8O8l8pKSDMxIUTJQTEwUiZmZlBEzMyV/gPwBUmZGzJTMzIjIxMTgDqSUGBpISl7y3qqz6/Y4z3nOWXc/Z+3ffj6n7uTe/dvrtz5r3f1tv1yKHwECBAgQ6BC41FGjhAABAgQIRIDYBAQIECDQJSBAutgUESBAgIAAsQcIECBAoEtAgHSxKSJAgAABAWIPECBAgECXgADpYlNEgAABAgLEHiBAgACBLgEB0sWmiAABAgQEiD1AgAABAl0CAqSLTREBAgQICBB7gAABAgS6BARIF5siA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KbjauO2dxi3HmqhxCBAgsGSBnovpEuYzvRPZ1ctpc5tqW6i0zyf9CBAgQKBDoGqATHcFu6Y8BcU3m09lO3iUECBAgMBpApUDxKoSIECAwEABATIQ39AECBCoLCBAKq+e3gkQIDBQQIAMxDc0AQIEKgsIkMqrp3cCBAgMFBAgA/ENTYAAgcoCAqTy6umdAAECAwUEyEB8QxMgQKCygACpvHp6J0CAwEABATIQ39AECBCoLCBAKq+e3gkQIDBQQIAMxDc0AQIEKgsIkMqrp3cCBAgMFBAgA/ENTYAAgcoCAqTy6umdAAECAwUEyEB8QxMgQKCygACpvHp6J0CAwEABATIQ39AECBCoLCBAKq+e3gkQIDBQQIAMxDc0AQIEKgsIkMqrp3cCBAgMFBAgA/ENTYAAgcoCAqTy6umdAAECAwX+AwgEXkzfHpKFAAAAAElFTkSuQmCC"
13. State: "NV"
14. Status: "Signed"
15. Street: "11 ABC"
16. TargetCMAID: "54AAFF2ECAFF4410E1008000A7692971"
17. Year: 2015
18. ZipCode: "89201"
19. _disabledStates: Object
20. _displayOrderLimit: Object
21. _recallState: "fsop.outlet.review-sign.summary"
22. _validationStates: Object
23. __proto__: Object
Let me know in case I need to add more details.
TIA
If your object store has a key path, the object being stored must contain a value pointed at by that key path or must use a key generator ({autoIncrement: true}).
For example:
var store = db.createObjectStore('my_store', {keyPath: 'key'});
store.put({key: 11, value: 33}); // OK
store.put({value: 66}); // throws, since 'key' is not present
var store = db.createObjectStore('my_store', {keyPath: 'key', autoIncrement: true});
store.put({key: 11, value: 33}); // OK, key generator set to 11
store.put({value: 66}); // OK, will have auto-generated key 12
I have a text file which looks like this
{
"TYPE": "EMAIL",
"ITEMS": [
{
"SENT": "2016-02-01T19:03:02.00Z",
"SUBJECT": "UPCOMING EVENTS: ORIENTATION 2016",
"TIMEZONE": "AUSTRALIA/MELBOURNE",
"CONTENT": "WE'RE PLEASED TO BE WORKING WITH RMIT LINK'S ORIENTATION TEAM AND RUSU TO WELCOME ALL NEW STUDENTS TO CAMPUS THROUGH A SERIES OF EXCITING ORIENTATION EVENTS. THIS EMAIL SERVES AS A NOTIFICATION TO MAKE SURE YOU KNOW WHEN THE MAJOR EVENTS ARE OCCURRING, TO ENSURE THEY DON'T INTERRUPT YOUR WORK AND SO THAT YOU ARE ABLE TO ENCOURAGE ALL NEW STUDENTS TO ATTEND. BRUNSWICK ALL STUDENTS WELCOME, 23 FEBRUARY 12 - 1:30PM BRUNSWICK COURTYARD. BUNDOORA ALL STUDENTS WELCOME, 24 FEBRUARY 12 - 2PM BUNDOORA WEST CONCOURSE. CITY ALL STUDENTS WELCOME, 25 FEBRUARY 11AM - 2:30PM ALUMNI COURTYARD, UNIVERSITY WAY. RUSU WELCOME BASH, 25 FEBRUARY 4PM - 9PM ALUMNI COURTYARD. CITY CLUBS DAY, 3 MARCH 11AM - 2PM ALUMNI COURTYARD, UNIVERSITY WAY."
},
{
"SENT": "2016-03-03T19:03:02.00Z",
"SUBJECT": "PROJECT 1 FIRST TIME MEETING",
"TIMEZONE": "AUSTRALIA/MELBOURNE",
"CONTENT": "EARLY NEXT WEEK IS GOOD FOR US. HOW ABOUT MONDAY 11AM?"
},
{
"SENT": "2016-03-03T19:03:02.00Z",
"SUBJECT": "PROJECT 1 FIRST TIME MEETING",
"TIMEZONE": "AUSTRALIA/MELBOURNE",
"CONTENT": "EARLY NEXT WEEK IS GOOD FOR US. HOW ABOUT TUESDAY 11:30 AM?"
},
}
I'm trying to extract the information making ITEMS as an array of Hashes. So that i can access the values for sent subject timezone and etc.
I have tried this it doesnt work. Any help?
my #AoH ;
while ( <> ) {
my $rec = {};
for my $field ( split ) {
(my $key, my $value) = split /:/, $field;
$rec->{$key} = $value;
}
push #AoH, $rec;
}
That's JSON data (JavaScript Object Notation) except that the very last comma , should be a closing square bracket ]. Use the JSON module to decode it into a Perl data structure
This program shows the principle. It prints just the subject line of each item, but I think you get the idea
use strict;
use warnings 'all';
use JSON qw/ decode_json /;
my $json = do {
open my $fh, '<:raw', 'text_file.txt' or die $!;
local $/;
<$fh>;
};
my $data = decode_json($json);
my $items = $data->{ITEMS};
for my $item ( #$items ) {
print $item->{SUBJECT}, "\n";
}
output
UPCOMING EVENTS: ORIENTATION 2016
PROJECT 1 FIRST TIME MEETING
PROJECT 1 FIRST TIME MEETING
I have a Google Sheets spreadsheet. In Column B, I have a list of strings that are either dates or ranges of dates in the format month/date. For example:
7/26
7/27-7/31
8/1
8/2
8/3-8/5
I want to create an array with the first date on the left and the second date (if any) on the right. If there's no second date, it can be left blank. This is what I want:
[7/26,]
[7/27,7/31]
[8/1,]
[8/2,]
[8/3,8/5]
I've tried:
var r = 'B'
var dateString = sheet.getRange(dateColumns[r] + '1:' + dateColumns[r] + lastRow.toString()).getValues();
var dateArr = Utilities.parseCsv(dateString, '-');
But that just keeps concatenating all values. Also if it's possible to put the output in a date format that would be great too.
This was a funny exercise to play with...
Here is a code that does what you want :
function test(){
convertToDateArray('7/26,7/27-7/31,8/1,8/2,8/3-8/5');
}
function convertToDateArray(inputString){
if(typeof(inputString)=='string'){inputString=inputString.split(',')}; // if input is a string then split it into an array using comma as separator
var data = [];
var datesArray = [];
for(var n in inputString){
if(inputString[n].indexOf('-')==-1){inputString[n]+='-'};// if only 1 field add an empty one
data.push(inputString[n].split('-'));// make it an array
}
Logger.log(data);//check
for(var n in data){
var temp = [];
for(var c in data[n]){
Logger.log('data[n][c] = '+ data[n][c]);
var date = data[n][c]!=''? new Date(2014,Number(data[n][c].split('/')[0])-1,Number(data[n][c].split('/')[1]),0,0,0,0) : '';// create date objects with right values
Logger.log('date = '+date);//check
temp.push(date);
}
datesArray.push(temp);//store output data in an array of arrays, ready to setValues in a SS
}
Logger.log(datesArray);
var sh = SpreadsheetApp.getActive().getActiveSheet();
sh.getRange(1,1,datesArray.length,datesArray[0].length).setValues(datesArray);
}
Logger result for datesArray :
[[Sat Jul 26 00:00:00 GMT+02:00 2014, ], [Sun Jul 27 00:00:00 GMT+02:00 2014, Thu Jul 31 00:00:00 GMT+02:00 2014], [Fri Aug 01 00:00:00 GMT+02:00 2014, ], [Sat Aug 02 00:00:00 GMT+02:00 2014, ], [Sun Aug 03 00:00:00 GMT+02:00 2014, Tue Aug 05 00:00:00 GMT+02:00 2014]]