JSON Import with Javascript, how to skip deferred exception? - json

I have written an javascript importer for a external json dataset
<script type="text/javascript" src="data.json"></script>
var importData = JSON.stringify(data);
var importCompany = data.report.company.name;
if(importCompany != ''){
jQuery('.company .name').text(importCompany);
}
All working perfectly :D
My issue is when I update the script to read data2.json and data.report.company.name doesn't exist, I get this error in the developer console
jQuery.Deferred exception: Cannot read property 'name' of undefined TypeError: Cannot read property 'name' of undefined
How do i overcome this issue?
Thanks
EDIT
data.json (external)
var data = {
"report": {
"company": {
"name": "XXX"
"other": "123"
},
"information": "GB-0-01777777",
"references": "2018-06-26T07:48:41.104Z"
}
data2.json (external)
var data = {
"report": {
"company": {
"other": "123"
},
"information": "GB-0-01777777",
"references": "2018-06-26T07:48:41.104Z"
}

Related

Google Apps Script - GoogleJsonResponseException: API call to sheets.spreadsheets.values.update failed with error: Invalid values[1][0]

the goal is to query fields inside a JSON object . But when executed the error above is throwned.
Dialogflow is integrated inside Slack as an App. The Google Apps Script is the web app. Here is the code:
//Writes in a sheet the Slack User id
function doPost(e) {
//Parse incoming JSON from Dialogflow into an object
var dialogflow = JSON.parse(e.postData.contents);
//Extracts userId from Slack
var desiredField = dialogflow.originalDetectIntentRequest.payload.data.event.user;
//Instantiates Sheets function
var valueRange = Sheets.newValueRange();
//Value to insert in cell
var values = [[ desiredField]];
valueRange.values = values;
//Inserts value in cell
var result = Sheets.Spreadsheets.Values.update(valueRange, 'XXX-YYY-ZZZ', 'rangeReceivingData', {valueInputOption: 'RAW'});
}
and here's the incoming JSON:
{
"responseId": "XXX-YYY-ZZZ",
"queryResult": {
"queryText": "oi",
"action": "input.welcome",
"parameters": {
},
"allRequiredParamsPresent": true,
"fulfillmentText": "Oi!",
"fulfillmentMessages": [{
"text": {
"text": ["Oi!"]
}
}],
"outputContexts": [{
"name": "projects/test-agent-xxyy/agent/sessions/xxx-yyy-zzz/contexts/__system_counters__",
"parameters": {
"no-input": 0.0,
"no-match": 0.0
}
}],
"intent": {
"name": "projects/test-agent-xxyy/agent/intents/xxx-yyy-zzz",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1.0,
"languageCode": "pt-br"
},
"originalDetectIntentRequest": {
"source": "slack",
"payload": {
"data": {
"event_time": "1589561467",
"api_app_id": "xxxyyyzzz",
"type": "event_callback",
"event": {
"event_ts": "1589561467.000200",
"team": "xxxyyyzzz",
"blocks": [{
"type": "rich_text",
"block_id": "xxxyyyzzz",
"elements": [{
"elements": [{
"text": "oi",
"type": "text"
}],
"type": "rich_text_section"
}]
}],
"ts": "1589561467.000200",
"channel_type": "im",
"client_msg_id": "xxx-yyy-zzz",
"text": "oi",
"type": "message",
"channel": "xxxyyyzzz",
"user": "T1H2E3G4O5A6L7"
},
"authed_users": ["XXXYYYZZZ"],
"event_id": "xxxyyyzzz",
"token": "xxxyyyzzz",
"team_id": "xxxyyyzzz"
}
}
},
"session": "projects/test-agent-xxyy/agent/sessions/xxx-yyy-zzz"
}
also, the fulfillment response in dialogflow have this weird formating:
fields {
key: "action"
value {
string_value: "input.welcome"
}
} ... (this is inside the sheets api error response)
When debuging it was possible to query the respondeId field (the first field from the incoming JSON). It looks that the program is taking lots of processing time on queryng further fields and in the end it throws the error. Any suggestion?
Documentation references:
Writing in Sheets
Handling POST requests in apps scripts
Dialogflow documentation on webhooks
Thanks in advance!
Error, solved. First, point:
It was possible to recover the received JSON from the webhook by using JSON.stringify:
function doPost(e) {
//Parse incoming JSON from Dialogflow
var dialogflow = JSON.parse(e.postData.contents);
//Stringify webhook after parsing
var desiredField = JSON.stringify(dialogflow);
//Outputs value in sheet
var valueRange = Sheets.newValueRange();
//Value to insert in cell
var values = [[ desiredField]];
valueRange.values = values;
//Inserts value in cell
var result = Sheets.Spreadsheets.Values.update(valueRange, 'spreadSheetId', 'range',
{valueInputOption: 'RAW'});
}
The incoming JSON was as expected then it was just a matter of querying the desired field:
from this:
//Stringify webhook after parsing
var desiredField = JSON.stringify(dialogflow);
to this:
//Extracts userId from Slack
var desiredField = dialogflow.originalDetectIntentRequest.payload.data.event.user;
Error solved!

Google Apps Script - Unable to query property from JSON data

dialogflow sends the following:
{
"responseId": "XXX-YYY-ZZZ",
"queryResult": {
"queryText": "random text",
"parameters": {
"command": "do it"
},
"allRequiredParamsPresent": true,
"fulfillmentText": "Sorry, can't understand it.",
"fulfillmentMessages": [
{
"text": {
"text": [
"Sorry, can't understand it."
]
}
}
],
"outputContexts": [
{
"name": "projects/xxx-vyyy/agent/sessions/xxx-yyy-zzz/contexts/__system_counters__",
"parameters": {
"no-input": 0,
"no-match": 0,
"command": "do it",
"command.original": "do it"
}
}
],
"intent": {
"name": "projects/xxx-vyyy/agent/sessions/xxx-yyy-zzz",
"displayName": "testCommands"
},
"intentDetectionConfidence": 1,
"languageCode": "en"
},
"originalDetectIntentRequest": {
"payload": {}
},
"session": "projects/xxx-vyyy/agent/sessions/xxx-yyy-zzz"
}
TypeError: Cannot read property 'parameters' of undefined (line 5, file "this-file")
and the goal is to query the command field. This is the current code:
function doPost(e) {
//EXTRACTION
var dialogflow = e.postData.contents;
var desiredField = dialogflow.queryResult.parameters.command;
}
but then this error thrown:
TypeError: Cannot read property 'parameters' of undefined (line 4, file "this-file")
I tried JSON.stringify(e) and e.postData.contents, but still not working.
Documentation on doPost() https://developers.google.com/apps-script/guides/web
and WebhookRequest sent by dialogflow https://cloud.google.com/dialogflow/docs/fulfillment-webhook#webhook_request
Thanks in advance!
At doPost(e), e.postData.contents is not parsed as JSON object. I think that your error message is due to this. So how about the following modification using JSON.parse()?
Modified script:
function doPost(e) {
//EXTRACTION
var dialogflow = JSON.parse(e.postData.contents); // Modified
var desiredField = dialogflow.queryResult.parameters.command;
}
Reference:
Web Apps

get json object attribute with 'dot' in name

*** Problem solved : json.stringify was the problem.. much easier to handle when its gone.
var DBName = result['Document']['SW.Blocks.GlobalDB']['AttributeList']['Name'];
I have a xml file which describes a datablock from a PLC and want to get specific values with JS.
I converted it with xml2js module, so i have a json object to work with.
{
"Document": {
"Engineering": {
"$": {
"version": "V15"
}
},
"SW.Blocks.GlobalDB": {
"$": {
"ID": "0"
},
"HeaderAuthor": "",
"HeaderFamily": "",
"HeaderName": "",
"HeaderVersion": "0.1",
"Interface": {
...
...
"Name": "datentypen",
"Number": "6",
"ParameterModified": {
"_": "2018-09-05T11:49:37.0862092Z",
"$": {
"ReadOnly": "true"
}
},
}
}
I want to print out the "Name" and the "Number", which are part of the "AttributeList".
So how to handle with the "SW.Blocks.GlobalDB"?
Getting error : "TypeError: Cannot read property 'SW' of undefined"
var fs = require('fs');
var xml2js = require('xml2js');
var xml = fs.readFileSync('datentypen.xml');
var parser = new xml2js.Parser({explicitArray: false});
parser.parseString(xml, function(err, result) {
if (err) {
console.error('xml2js.parse error: ',err);
} else {
var injson = JSON.stringify(result,null,3);
console.log(injson);
// var injson2 = JSON.parse(injson);
// var DBnummer = injson.Document.SW.Blocks.GlobalDB.AttributeList["Name","Number"];
// console.log(DBNummer);
};
});
I read a lot about this theme but didnt found a concrete answer..
When i write ["SW.Blocks.GlobalDB"], an error about [ comes around.
Can you try reading the JSON array using Key-Value pair? I had similar issues but with a different programming language.

Nested JSON Schema Validation in Postman

I want to validate a Nested JSON Schema in Postman.
Here is the code.
const testSchema = {
"name": [
{
"first_name": "Alpha",
"last_name": "Bravo"
},
{
"first_name": "Charlie",
"last_name": "Delta"
},
],
"age": "23",
"color": "black"
};
const showData = {
"required": ["name", "age"],
"properties": {
"name": [
{
"required": ["first_name"]
}
],
},
};
pm.test("Nested Schema Test", function () {
pm.expect(tv4.validate(testSchema, showData)).to.be.true;
});
Currently, this code returns test as true.
I am unable to test the "name" array objects' keys.
Even upon passing this:
"required": ["fst_nae"] //wrong key name
it returns true.
I would just check in easy way via:
pm.test("your name", function () {
pm.expect(testSchema.name[0].first_name && testSchema.name[1].first_name
).to.eql('Alpha' && 'Charlie')
});
and you successfully validated these fields
or use this expect to organize your code of your choice
tiny validator i.e. tv4.validate is having issues in their library. Another option is to use AJV (you can search it on github).

Use Apps Script URLFetchApp to access Google Datastore Data

I want to experiment with Google Datastore via Apps Script because I have a current solution based on Google sheets that runs into timeout issues inherent in constantly transacting with Drive files. I've created a test project in Google cloud with a service account and enabled library MZx5DzNPsYjVyZaR67xXJQai_d-phDA33
(cGoa) to handle the Oauth2 work. I followed the guide to start it up here and got all the pertinent confirmation that it works with my token (and that removing the token throws an 'authentication failed prompt').
Now I want to start with a basic query to display the one entity I already put in. I can use the API Explorer here and run this query body:
{
"query": {}
}
and get this result:
{
"batch": {
"entityResultType": "FULL",
"entityResults": [
{
"entity": {
"key": {
"partitionId": {
"projectId": "project-id-5200707333336492774"
},
"path": [
{
"kind": "Transaction",
"id": "5629499534213120"
}
]
},
"properties": {
"CommentIn": {
"stringValue": "My First Test Transaction"
},
"Status": {
"stringValue": "Closed"
},
"auditStatus": {
"stringValue": "Logged"
},
"User": {
"stringValue": "John Doe"
},
"Start": {
"timestampValue": "2017-08-17T18:07:04.681Z"
},
"CommentOut": {
"stringValue": "Done for today!"
},
"End": {
"timestampValue": "2017-08-17T20:07:38.058Z"
},
"Period": {
"stringValue": "08/16/2017-08/31/2017"
}
}
},
"cursor": "CkISPGogc35whh9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"version": "1503004124243000"
}
],
"endCursor": "CkISPGogc35wcm9qZWN0LWlkLTUyMDAxxDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"moreResults": "NO_MORE_RESULTS"
}
}
I try to do the same thing with this code:
function doGet(e)
{
var goa = cGoa.GoaApp.createGoa('Oauth2-Service-Account',
PropertiesService.getScriptProperties()).execute(e);
if(goa.hasToken()) {var token = goa.getToken();}
var payload = {"query":{}}
;
var result = UrlFetchApp.fetch('https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
method: "POST",
headers: {authorization: "Bearer " + goa.getToken()},
muteHttpExceptions : true,
payload: payload
});
Logger.log(result.getBlob().getDataAsString());
}
and get this error in the logger:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
If I try to use another word such as 'resource' or 'GqlQuery', I get this error:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message."
}
]
}
]
}
}
I can't tell from the API Documentation what my syntax is supposed to be. Can anyone tell me how to compile a functional request body from Apps Script to Datastore?
You need to set the contentType of your payload as well as stringify your JSON payload as follows:
var result = UrlFetchApp.fetch(
'https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
'method':'post',
'contentType':'application/json',
'headers': {authorization: "Bearer " + goa.getToken()},
'payload':JSON.stringify(payload)
}
);