Google Slides API deleteObject() when object not exists - google-apps-script

I want to update an existing object/image in a Google Slide. This works as long as the object exists:
var requests = [
{
"deleteObject": {
"objectId": 'image01'
}
},
{
"createImage": {
"url": imageUrl,
"objectId": 'image01',
"elementProperties": {
"pageObjectId": pageId,
"size": {
"width": {
"magnitude": 250,
"unit": "PT"
},
"height": {
"magnitude": 250,
"unit": "PT"
}
},
"transform": {
"scaleX": 1,
"scaleY": 1,
"translateX": 200,
"translateY": 100,
"unit": "PT"
}
}
}
}
];
var response = Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
However, if a user previously deleted the object in the presentation, it is not re-created.
The following error message appear:
Invalid requests[0].deleteObject: The object (image01) could not be
found.
How can I query whether an object exists in presentation?

How about retrieving a object list using slides.presentations.get? In order to confirm whether objects exist, it uses slides/pageElements/objectId for fields of slides.presentations.get. You can know the exist of objects using the object list.
Sample script :
var response = Slides.Presentations.get(presentationId);
response.slides.forEach(function(e1, i1){
e1.pageElements.forEach(function(e2){
Logger.log("Page %s, objectId %s", i1 + 1, e2.objectId);
});
});
Result :
Page 1.0, objectId ###
Page 2.0, objectId ###
Page 3.0, objectId ###
If this was not useful for you, I'm sorry.
Edit :
If you want to search a value from whole JSON, you can use following simple script. When value2 is included in sampledata, ~JSON.stringify(sampledata).indexOf('value2') becomes true. In this sample, ok is shown, because value2 is included in sampledata.
But it's a bit of a stretch. If you can know the complete structure of JSON, I think that the compare of value using key is better.
var sampledata = {key1: "value1", key2: "value2"};
if (~JSON.stringify(sampledata).indexOf('value2')) {
Logger.log("ok")
}

Related

I can't reach JSON value Flutter

I can't reach my returned JSON data value. I'm using get method for reaching and server returns the JSON with 200 but when I try to reach JSON value it gives error.
My JSON:
{
"user": [
{
"id": 2,
"userName": "Mehmet",
"email": "personal#test.com",
"sys_role": 3,
"tckn": "00000000000",
"fk_parkID": 81
}
],
"parks": [
{
"parkID": 1,
"parkName": "Park Name",
"latitude": 42,
"longitude": 29,
"fk_regionID": 2
}, // 107 more parks like the up one.
]
}
I've tried this for reaching "userName" value from "user".
var selectedUserInfo;
var parksInfo;
selectUser(id) async { // This is selecting a person for doing some process on his/her account.
var result = CallApi().getData('admin/user/${id}', _setHeaders());
selectedUserInfo = jsonDecode(result.body)["user"][0]["userName"];
parksInfo = jsonDecode(result.body)["parks"];
setState(() {
});
}
When I
print(selectedUserInfo)
it returns null.
Your getData() method is probably an asynchronous method (Future).
If you don't wait for it, the result will be null, so the selectedUserInfo.
You should add the await keyword like this :
var result = await CallApi().getData('admin/user/${id}', _setHeaders());
I hope that will solve your issue

getting data from an array of objects inside array JSON data

I have trouble taking data from an API set. The body if viewed in Postman / Insomnia is as follows
{
"responses": {
"log": [
{
"id": 123,
"date": "2022-01-01T01:12:12.000Z",
"type": "online",
"details": [{
"detailId": "123-1",
"note": "success",
}]
},
{
"id": 124,
"date": "2022-01-01T01:12:12.000Z",
"type": "offline",
"details": [{
"detailId": "123-2",
"note": "failed",
}]
}
]
}
}
I want to take all data from log, as well from details. I used
adapt(item: any) {
return {
id: item.id,
date: item.date,
details: {
detailId: item.details.detailId,
note: item.details.note,
},
};
}
this returns id and date just fine. I also have a query to filter it based on type (online or offline), basically adding &type= into the API. It works for the online, but it returns detailId is undefined for offline (I used the same body, adapter and API minus the query for both data)
details is an array of object if you want to adapt it you need to do it iteratively.
adapt(item: any) {
const details = item.details.map(d => {detailId: d.id, note: d.note, …});
return {
id: item.id,
date: item.date,
details
};
}
Found the answer, apparently to make sure that I can get every value is to add ? after the [0], so it should be
details: {
detailId: item.details[0]?.detailId,
note: item.details[0]?.note,
},

JSON schema reference key value as the type of the field [duplicate]

I'm trying to validate json files which have an element that has a property which contains a value that should exist in another part of the json. I'm using jsonschema Draft 07.
This is a simple little example that shows the scenario I'm trying to validate in my data.
{
"objects": {
"object1": {
"colorKey": "orange"
}
},
"colors": {
"orange": {
"red": "FF",
"green": "AF",
"blue": "00"
}
}
}
How can I validate that the 'value' of colorKey (in this case 'orange') actually exists as a property of the 'colors' object? The data isn't stored in arrays, just defined properties.
For official JSON Schema...
You cannot check that a key in the data is the same as a value of the data.
You cannot extract the value of data from your JSON instance to use in your JSON Schema.
That being said, ajv, the most popular validator, implements some unofficial extensions. One of which is $data.
Example taken from: https://github.com/epoberezkin/ajv#data-reference
var ajv = new Ajv({$data: true});
var schema = {
"properties": {
"smaller": {
"type": "number",
"maximum": { "$data": "1/larger" }
},
"larger": { "type": "number" }
}
};
var validData = {
smaller: 5,
larger: 7
};
ajv.validate(schema, validData); // true
This would not work for anyone else using your schemas.

jqgrid read in embedded json objects

Hey guys so I am currently using jqgrid with json data and it currently reads in fine but i am having some difficulties getting an embeded object to read into the grid. So my json data looks something like this:
{"total":1,"page":"1","records":1,"rows":[{"Cell1":1,"Cell2":"stuff","Cell3":{"date":"2013-06-02 10:56:00","timezone_type":3,"timezone":"UTC"}}]}
Does anyone know how i can get jqgrid to read in Cell3 as one piece of data and interpret it to just display the date and time?
my current json reader is as follows:
jsonReader : {
root:"rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
id: "0"
}
Thanks again everyone
First of all the options jsonReader: {repeatitems: false, id: "0"} are incorrect. Integer values of id can be used in case of usage default repeatitems: true setting. In the case the data which represent the row of the grid looks like array ["1", "Cell2"] and not as object with named properties {"Cell1": 1, "Cell2": "stuff"}. You should use jsonReader: {repeatitems: false, id: "Cell1"} if Cell1 contains the value which you want to use as unique id of the row of the grid.
Now back to your main question. I recommend you to change format of the data from
{
"total": 1,
"page": "1",
"records": 1,
"rows": [
{
"Cell1": 1,
"Cell2": "stuff",
"Cell3": {
"date": "2013-06-02 10:56:00",
"timezone_type": 3,
"timezone": "UTC"
}
}
]
}
to
{
"total": 1,
"page": "1",
"records": 1,
"rows": [
{
"Cell1": 1,
"Cell2": "stuff"
}
],
"userdata": {
"1": {
"date": "2013-06-02 10:56:00",
"timezone_type": 3,
"timezone": "UTC"
}
}
}
I want comment my suggestion so that it could be clear for other users too. The column Cell1 contains the id. The structure of userdata which I suggest is the map from rowid (the value of Cell1) and the custom information which you need save as "Cell3" originally.
If you need somewhere in your code to have the "Cell3" value the code will be like below
onSelectRow: function (rowid) {
var cell3 = $(this).jqGrid("getGridParam", "userData")[rowid];
// now you can use cell3 which coniains the object like
// {
// "date": "2013-06-02 10:56:00",
// "timezone_type": 3,
// "timezone": "UTC"
// }
}

Using QUERY URL to group data before sending to Google Apps Script dashboard

I have a Google Spreadsheet, with say a key 'ABCKEY' and would like to perform the QUERY (SQL) function on the data before using the data in a Google Apps Script dashboard.
var ss = SpreadsheetApp.openById('ABCKEY');
var mydata = ss.getDataRange();
This article explains how one can use the QUERY feature on the data in the spreadsheet to produce grouped data.
The following query produces the correct grouped data I would like to use as the data source of my Google Apps Script dashboard:
https://spreadsheets.google.com/a/mybusinessappdomain.com/tq?key=ABCKEY&tq=select%20A%2CC%2Csum(F)%2Csum(G)%20group%20by%20A%2C%20C
I would therefore essentially like to populate the mydata variable above with the result from the above SQL query, which produces a JSON output string.
How can this be accomplished?
The approach I propose is this:
Use UrlFetchApp.fetch() to get the results of the query uri into a variable in your script. The query URI returns javascript to set results for the google visualization service.
Remove any extraneous content in the result, leaving only the JSON representation of the query results. A simple regex extraction can do this, and then we can parse the extracted string into a JSON object.
Decode the JSON object into a two-dimensional array, mydata. This requires some understanding of how the table is represented as a JSON object in the visualization query.
The JSON query result is structured like this:
{
"version": "0.6",
"status": "ok",
"sig": "862651648",
"table": {
"cols": [
{
"id": "A",
"label": "",
"type": "string",
"pattern": ""
},
{
"id": "D",
"label": "Population Density",
"type": "number",
"pattern": "#0.###############"
}
],
"rows": [
{
"c": [
{
"v": "Indonesia"
},
{
"v": 117,
"f": "117"
}
]
},
{
"c": [
{
"v": "China"
},
{
"v": 137,
"f": "137"
}
]
},
{
"c": [
{
"v": "Nigeria"
},
{
"v": 142,
"f": "142"
}
]
},
{
"c": [
{
"v": "Pakistan"
},
{
"v": 198,
"f": "198"
}
]
},
{
"c": [
{
"v": "India"
},
{
"v": 336,
"f": "336"
}
]
},
{
"c": [
{
"v": "Japan"
},
{
"v": 339,
"f": "339"
}
]
},
{
"c": [
{
"v": "Bangladesh"
},
{
"v": 1045,
"f": "1045"
}
]
}
]
}
}
You'll notice that the table object consists of an array of cols objects that describe the columns in the table. For your array, the portion that you're interested in is the label for the column.
After that, the table object contains an array of rows objects, each with an array of c objects with the data for each column in the row. For your array, it's the v or value that you're interested in. (f contains a formatted version of the same data)
So our parser will iterate through the column headers first, then through each row of the table, pushing the values-of-interest into a two-dimensional array, mydata.
For this example, I'm accessing the public spreadsheet used in the Interactive Code Sample provided in the Query Language Reference, and also using their sample query. I've written the example so it can be easily modified to access your own spreadsheet with your own query. Here's the code:
// Specify the spreadsheet key and the query to be retrieved
var ssKey = 'pCQbetd-CptGXxxQIG7VFIQ';
var query = encodeURIComponent('SELECT A,D WHERE D > 100 ORDER BY D');
// Build url to peform query
var url = 'http://spreadsheets.google.com/tq?key=%KEY%&tq=%QUERY%'
.replace('%KEY%',ssKey)
.replace('%QUERY%',query);
// Use UrlFetchApp to get the results of the query as a string.
var response = UrlFetchApp.fetch(url);
var content = response.getContentText();
//Logger.log(content);
// Extract the JSON object from the response. Note that the response contains
// multiple lines of Javascript, and that it's the second line that has our
// data table in it.
var regex = /.*google.visualization.Query.setResponse\((.*)\)/g
var jsonContent = regex.exec(content)[1];
Logger.log(jsonContent);
var objectContent = Utilities.jsonParse(jsonContent);
var numCols = objectContent.table.cols.length;
var numRows = objectContent.table.rows.length;
// Decode objectContent into a two-dimensional array.
var mydata = []
// Start with the header row.
mydata[0] = [];
for (var col = 0; col < numCols; col++ ) {
mydata[0].push(objectContent.table.cols[col].label);
}
// Then data rows
for (var row = 0; row < numRows; row++) {
mydata[row+1] = [];
for (var col = 0; col < numCols; col++ ) {
mydata[row+1].push(objectContent.table.rows[row].c[col].v);
}
}
// Done - mydata is now a two-dimensional array with the results of the query
debugger; // If debugging, pause to examine results
Depending on what you're planning to use the data for in your dashboard, you may just want to use the table object after the call to jsonParse().
I do not think the json parser var objectContent = Utilities.jsonParse(jsonContent) would work with those visualization query response having date as one of the cell value such as the below example
{
"v": newDate(2013,
11,
31),
"f": "31-Dec-2013",
"p": {
"style": "color: rgb(0, 0, 0);font-family:Dialog;"
}
}