How to use API and JSON Correctly? - javascript

I have a bot that is built with botkit and using a Zendesk api to pull information.
I have a function that asks a user for a search term and the bot searches relevant information about that search term. It pulls the information from the Zendesk API and outputs the answer.
I don't understand when accessing the object's value some values are able to be outputted while some are not.
For example, if the user submits 'jim' as the search term. I can pull relevant information by doing this: tickets[0].id + tickets[0].priority + tickets[0].subject + tickets[0].description.
When I do something like this:
tickets[4]- I get undefined values.
The full code of what I'm trying to do is this:
controller.hears(['SEARCH TICKET',/search ticket/gi, /^.{0,}jirabot.
{0,}$/],
['direct_message','direct_mention','mention','ambient'],function(bot,message)
{
// start a conversation to handle this response.
bot.startConversation(message,function(err,convo) {
convo.ask('What are you looking for?',function(response,convo) {
zendesk.search.list('query='+response.text+'&sort_by=priority&sort_order=desc').then(function(tickets){
console.log(tickets);
bot.reply(message, 'The Ticket ID Number: ' + tickets[3] + tickets[0].id + '\n The Ticket Priority: ' + tickets[0].priority + '\n The Ticket Subject: ' + tickets[0].subject + '\n The Ticket Description: \n'+ tickets[0].description + '\n');
convo.next();
}
});
});
});
});
Here is what the JSON looks like:
{
"results": [(in here is the information like ticket subject, priority, id,
etc.],
"facets": null,
"next_page": null,
"previous_page": null,
"count": 2
}
How do I get the value for count? I get undefined when I do tickets[4].

To access the properties of the JSON you've shown, you wouldn't use index values like 0,1,2,3. Instead you'd write ticket["results"], ticket["count"], ticket["<PropNameHere>"]

Related

Receiving String saved wrong in the database

I have an API using Express.js that receives data from Sigfox(A service for IoT) and inserts the data into the SQL Server Express database, this data comes in 4 different URL with this format:
http://servername:port/api/mediciones/sigfox_libelium/aire/2059E7/230934644ae17a8441/1626762070/9
My solution to insert all the data, is to create an array and fill it with the parsed data from the all 4 URL.
[
'2059E7',
64,
16.559999465942383,
98.3505859375,
100161.21875,
1.7199997901916504,
3.1599998474121094,
16.219999313354492
]
When the last request comes and the array is filled, an Insert is made into the database table:
.query("INSERT INTO medicionAire(fecha,id, bateria, temperatura, humedad, presionatmosferica, pm1, pm2, pm10) VALUES(SYSDATETIME()," + dimensiones[0] + ", "+ dimensiones[1] + ", " + dimensiones[2] + ", " + dimensiones[3] + ", " + dimensiones[4] + ", " + dimensiones[5] + ", " + dimensiones[6] + ", " + dimensiones[7] + ");")
where Dimensiones[] is the array filled with data.
ID should be "2059E7" like in the URL but when saved looks like this
EDIT: This is the Design of the table, column id is a Varchar, not a num, but looks like is being treated as a number
In your database the data type of id is a numeric type (float, int, decimal...) and therefore the value 2059E7, which is a mathematical notation for 2059 multiplied by 10000000 (7 zeroes).
SQL server returns a standard notation x.yEz or 2.059E+10.
You need to change the data type of the id column to be a text type (VARCHAR...)

How to get valid result from table.get using Dexie/IndexDB

I'm a PHP coder so not fully in the know with Javascript so possibly making a real schoolboy error here. I'm trying to facilitate some client side DB using Dexie & IndexDB. I can get values in using db.table.put and retrieve them all using db.table.toArray. However I seem to be struggling with getting individual records back out again. I'm trying to query for Keydata based on a form input. Heres my code, but it returns a TypeError cannot read property of undefined.
Here I can confirm in line 4 that my 'search2' variable contacts keyData (e.g. 1). But when used in line 5 it doesn't return a valid result. Can anyone see the issue?
function searchData(){
var search2;
search2 = document.getElementById('search2').value;
alert ("Id " + search2);
db.contacts.get(search2).then
(function (contact) {
alert ("Id " + contact.id + " : " + contact.title + " " + contact.forename + " " + contact.surname);
}).catch(function(error) {
alert ("Ooops: " + error);
});
}

How do I reference a value in an App Maker query (like I do in Apps Script)

I am writing a script to take a stock number, loop through existing stock numbers until a match is NOT found, then assign that unique stock number to the record. My problem is that the usual data[i][2] doesn't seem to reference a 'query' the same way that Apps Script would reference an array.
Fair warning, I'm trying to expand my Apps Script skills in to broader Javascript so I there's a good chance I'm doing it all wrong - I'm all ears if you tell me I'm doing this all incorrectly!
Using the log: data[i][2] gives me 'undefined' whereas data[2] gives me all fields of the third item in my query. Based on this I feel like I just need to learn how to reference it properly.
//Querying my datasource as 'var data'
var query = app.models.UsedVehicles.newQuery();
query.filters.ParentDealType._contains = prefix;
var data = query.run();
//Returns four records which is correct.
var testStockNo = prefix+month+countstring+year;
console.log("Test Stock Number " + j + ": " + testStockNo);
for (i = 0; i < data.length; i++){
console.log("data[i][2]: " + data[i][2]); //results: undefined
console.log("data[2]: " + data[2]); //results: all fields of 3rd query result.
if(data[i][2] === testStockNo){
k++;
break;
}else{
console.log("No Match");
}
}
Even if testStockNo equals the value in field:TStockNo, the log displays:
Test Stock Number 1: C1200118
data[i][2]: undefined
data[2]: Record : { TIndex: 8, TVin8: HS654987, TStockNo: null,
TParentStkNo: GSD6578, TYear: 2010, TMake: NISSAN, TModel: PICKUP,
TMileage: 24356, ParentDealType: C}
No Match
Issue/Solution:
query.run() returns array of records and NOT a array of arrays(2D). You should access the Record value using it's key instead of a index.
Snippets:
console.log("data[i][TStockNo]: " + data[i]['TStockNo']);
console.log("data[i].TStockNo: " + data[i].TStockNo);
console.log("data[2]: " + data[2]);
References:
Query#Run

MongoDB select and concatenate fields

I have a very basic question:
SELECT name, surname CONCAT(name, surname) AS name_surname from users;
How can I convert this SQL to MongoDB query?
During my search, I have decided that it is possible with aggregate framework due to concat, but what I received is only projection of concat(name, surname) not name, surname and concat(name, surname).
Final thing I got is this query:
db.inroamers.find().forEach(
function(o) {
print(o.LAC + '-' + o.CELL + ' ' + o.CHARGE + ' ' + o.WEEK);
})
but it does not give me proper json array.
Any suggestions?
Use the aggregation operations as below:
db.collection.aggregate([
{$project:{"name_surname":{$concat:["$name","-","$surname"]},"name":1,"surname":1}}
])

Contacts of Firefox OS problems with mozContacts.tel

I've been trying to get the contact name and last name and also get the cellphone number but when I am using the getAll() method the Console display this:
Found: Daniel Garcia [object Object]
As you can see it displays the Name + LastName + tel. Why does it display tel like [object Object]
Here is my code:
var allContacts = navigator.mozContacts.getAll({
sortBy: "givenName",
sortOrder: "ascending"
});
allContacts.onsuccess = function(event) {
if (cursor.result) {
if (cursor.result.familyName[0]== undefined) {
cursor.result.familyName[0]= "";
}
console.log("Found: " + cursor.result.givenName[0] + " " + cursor.result.familyName[0] + ' ' + cursor.result.tel[0]);
cursor.continue();
} else {
console.log("No more contacts");
}
}
tel here is an array of objects - a list of all the possible phone numbers for the contact. Each of this objects has several useful properties. In javascript when you are printing out an object it prints an object string representation (like [object Object]).
Check out docs to understand the structure of the tel object and get it printed the way you want: https://developer.mozilla.org/en-US/docs/Web/API/mozContact.tel
Thank you very much it work just like Aras and jamesh proposed
console.log("Found: " + cursor.result.givenName[0] + " " + cursor.result.familyName[0]+' '+JSON.stringify(cursor.result.tel[0]));
and the console display this:
"Found: Daniel Garcia {"type":["mobile"],"value":"8112441018"}"

Categories

Resources