json to javascript variable zendesk - javascript

I'm trying to retrieve the amount of open tickets from the zendesk api for a specific user. However I can't seem to get it to work. I keep getting this error:
Uncaught TypeError: Cannot read property '500' of undefined
The json format:
{
"user": {
"id": 500,
"url": "https://zendesk/api/v2/users/500.json",
"name": "Random name",
"email": "not important",
"created_at": "2016-05-18T15:26:43Z",
"updated_at": "2018-07-04T06:23:35Z",
"time_zone": "Brussels",
"phone": null,
"shared_phone_number": null,
"photo": {
"url": "https://google.com",
"id": 504,
"file_name": "keep-calm-and-shut-up-im-your-system-administrator.png",
"content_url": "https://google.com",
"mapped_content_url": "https://google.com",
"content_type": "image/png",
"size": 3298,
"width": 80,
"height": 50,
"inline": false,
"thumbnails": [
{
"url": "https://google.com",
"id": 90752965,
"file_name": "not important",
"content_url": "https://google.com",
"mapped_content_url": "https://google.com",
"content_type": "image/png",
"size": 3298,
"width": 32,
"height": 20,
"inline": false
}
]
},
"locale_id": 1005,
"locale": "nl",
"organization_id": 501,
"role": "admin",
"verified": true,
"external_id": null,
"tags": [],
"alias": "",
"active": true,
"shared": false,
"shared_agent": false,
"last_login_at": "2018-07-04T06:23:35Z",
"two_factor_auth_enabled": null,
"signature": "",
"details": "",
"notes": "",
"role_type": null,
"custom_role_id": null,
"moderator": true,
"ticket_restriction": null,
"only_private_comments": false,
"restricted_agent": false,
"suspended": false,
"chat_only": false,
"default_group_id": 503,
"user_fields": {
"agent_ooo": false
}
},
"open_ticket_count": {
"500": 15
}}
This is my javascript code:
<script>
function getJSON(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?
include=open_ticket_count');
console.log(gjson.open_ticket_count["500"]);
</script>
Can someone help me out? I'm not sure of what I'm doing wrong (the zendesk urls are the correct urls in the actual script and they can access it)
TLDR: I need to retrieve the variable from: open_ticket_count from a json.
Thank you!

Your getJSON function will not wait for the request to actually go through. A function like this would return the responseText only once it's finished:
const getJSON = function(url, callback) {
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
let status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
You can then use this to get the Zendesk JSON:
getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count', (status, gjson) => {
console.log(gjson.open_ticket_count["500"]);
});

Hard to say exacty without rest of the environment but I assume this will work:
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count'');
var jsonObj = JSON.parse(gjson); // assuming getJSON returns the json as string, this is async, make sure next row has the data needed on time or rewqork this as promise
console.log(jsonObj.open_ticket_count["500"]);
So basically call the entire JSON and then parse it from string to object before using it like object

The clue is in the error
Uncaught TypeError: Cannot read property '500' of undefined
Which says that gjson.open_ticket_count is undefined.
You haven't actually parsed the JSON and trying to get a property of a string not the parsed JSON.
Try parsing it first.
var gjson;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?include=open_ticket_count');
var gobj = JSON.parse(gjson);
console.log(gobj.open_ticket_count["500"]);

You need to parse the JSON in order to access it. Use below code
<script>
function getJSON(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
var gjson ;
gjson = getJSON('https://zendesk.com//api/v2/users/me.json?
include=open_ticket_count');
gjson = JSON.parse(gjson)
console.log(gjson.open_ticket_count["500"]);
</script>

Related

Looping over Json Array In JS

I am calling from an API to get the response in json format. I would like to loop through that response and only get the data once as it brings up results twice.
var url = "api call";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Authorization", "Bearer $token");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
Response in json I get is:
{
"next": "url",
"data": [
{
"profile_id": "00000000-0000-0000-0000-000000012f44",
"value": {
"signal": 0.61,
"connection": "radio_low_power",
"profile_id": "00000000-0000-0000-0000-000000013ee4"
},
"timestamp": "2022-07-22T14:52:37.359000Z",
"type": "seen_device"
},
{
"profile_id": "00000000-0000-0000-0000-000000012f44",
"value": 0.61,
"timestamp": "2022-07-22T14:52:37.359000Z",
"type": "connection_signal"
},
{
"profile_id": "00000000-0000-0000-0000-000000012f44",
"value": {
"signal": 0.58,
"connection": "radio_low_power",
"profile_id": "00000000-0000-0000-0000-000000013ee4"
},
"timestamp": "2022-07-22T14:37:32.096000Z",
"type": "seen_device"
},
...]}
I would like to loop and show only the type:"seen_device", value, timestamp.
This is what i've tried so far to loop the data:
for(let i = 0; i < xhr.length; i++) {
let obj = xhr.responseText[i];
console.log("hello");
console.log(xhr.responseText.data);
}
}};
Because you looping async data, means you are trying to loop when data is not present, you need to add check if the response is not undefined and data on which you want to loop should have length
putting a sample code
function loopOverDat(){
response && response.length && response.forEach(item => .....);
}

How to retrieve value in javascript

I am returning a json as shown below,
{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}
I am trying to get permissionsid value (it is occurred three places in the JSON), also forgot to mention in the original comment that these alphnumeric values in permissionid and userid are dynamics
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser['permissionId'];
When I am using the following, I am getting Cannot read properties of undefined (reading 'id')
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0].id;
When I am using the following, I am getting undefined
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions[0];
When I am using the following, I am getting [object%20Object]
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
var permission_id = userResponseParser.entities.permissions;
What I am missing here, couldn't find same kind of question
Why stringify and parse?
Anyway, it is more complex than you think
const obj = JSON.parse(str)
console.log(Object.values(obj.entities.users)[0].permissionId)
<script>
const str = `{
"entities": {
"permissions": {
"77de5140-9e1f-48b6-87a5-c80f12cd66d9": {
"id": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"role": "ADMIN",
"permissions": null,
"canAccessAllAccounts": true,
"allowedAccounts": null,
"createdAt": "2022-01-30T18:20:46.901Z",
"updatedAt": "2022-01-30T18:20:46.901Z",
"deletedAt": null
}
},
"users": {
"9bba4c96-781b-4012-9a48-071c1cb5ec24": {
"id": "9bba4c96-781b-4012-9a48-071c1cb5ec24",
"username": "246e6555eb16e3c8#ator.com",
"activeAccountId": "a979189d-6bef-41f9-b224-892fbeb0955b",
"enterpriseId": "9a69bba9-ed35-4589-8784-6b0e256bd7a0",
"permissionId": "77de5140-9e1f-48b6-87a5-c80f12cd66d9",
"firstName": "a48d1eb7270bb404",
"lastName": "e0aaa6d09e19",
"avatarUrl": null,
"sendBookingRequestEmail": true,
"isSSO": false,
"createdAt": "2022-01-30T18:20:46.999Z",
"updatedAt": "2022-01-30T18:20:46.999Z",
"deletedAt": null,
"permission": "77de5140-9e1f-48b6-87a5-c80f12cd66d9"
}
}
},
"result": "9bba4c96-781b-4012-9a48-071c1cb5ec24"
}`</script>
I see only 2 places, but in any cases remove this from your code
var res = JSON.stringify(response.body);
var userResponseParser = JSON.parse(res);
since your response data is parced already automatically
Since you can have several permissions or users , you can not get your data just using [0] or [1] since you don' t know how many users can be in the response. So try this code ( it was tested and working properly)
var permissionIds=[];
Object.values(response.entities.permissions).forEach(element => {
permissionIds.push(element.id)
});
var userIds=[];
Object.values(response.entities.users).forEach(element => {
userIds.push(element.id)
});

Ηow to extract particular data from JSON inside JSON object

A packet contains the data below but I need to extract the following part:
"data":"YOeNkAAg1wQAYjm/pg==
using JavaScript in node-red. How i can do this?
{
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent
{
\"appeui\":\"01-01-01-01-01-01-01-01\",
\"codr\":\"4/5\",
\"data\":\"YOeNkAAg1wQAYjm/pg==\",
\"datr\":\"SF7BW125\",
\"deveui\":\"39-31-37-33-5b-37-67-19\",
\"freq\":868.29999999999995,
\"gweui\":\"00-80-00-00-a0-00-24-6d\",
\"id\":0,
\"ipol\":true,
\"mhdr\":\"60e78d900020d704\",
\"mic\":\"6239bfa6\",
\"modu\":\"LORA\",
\"ncrc\":true,
\"opts\":\"\",
\"port\":0,
\"powe\":11,
\"rfch\":0,
\"seqn\":1239,
\"size\":13,
\"tmst\":3491353235,
\"twnd\":1
}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var src = {
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent {\"appeui\":\"01-01-01-01-01-01-01-01\",\"codr\":\"4/5\",\"data\":\"YOeNkAAg1wQAYjm/pg==\",\"datr\":\"SF7BW125\",\"deveui\":\"39-31-37-33-5b-37-67-19\",\"freq\":868.29999999999995,\"gweui\":\"00-80-00-00-a0-00-24-6d\",\"id\":0,\"ipol\":true,\"mhdr\":\"60e78d900020d704\",\"mic\":\"6239bfa6\",\"modu\":\"LORA\",\"ncrc\":true,\"opts\":\"\",\"port\":0,\"powe\":11,\"rfch\":0,\"seqn\":1239,\"size\":13,\"tmst\":3491353235,\"twnd\":1}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var payload = src.payload;
payload = JSON.parse(payload.substr(payload.indexOf('{')));
console.log(payload.data);
console.log('"data":"' + payload.data + '"');
var finalResult = {};
finalResult.data = payload.data;
console.log(JSON.stringify(finalResult));
And after removing this strange part JSON could look like this
{
"payload": {
"appeui": "01-01-01-01-01-01-01-01",
"codr": "4/5",
"data": "YOeNkAAg1wQAYjm/pg==",
"datr": "SF7BW125",
"deveui": "39-31-37-33-5b-37-67-19",
"freq": 868.3,
"gweui": "00-80-00-00-a0-00-24-6d",
"id": 0,
"ipol": true,
"mhdr": "60e78d900020d704",
"mic": "6239bfa6",
"modu": "LORA",
"ncrc": true,
"opts": "",
"port": 0,
"powe": 11,
"rfch": 0,
"seqn": 1239,
"size": 13,
"tmst": 3491353235,
"twnd": 1
},
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
If the resualt always look like data...== you can search in the payload for the content between data and == with
var res = array.payload.substring(
response.payload.lastIndexOf("data") + -1,
response.payload.lastIndexOf("==") + 3
);
var response = {
"payload": "lora/01-01-01-01-01-01-01-01/39-31-37-33-5b-37-67-19/packet_sent {\"appeui\":\"01-01-01-01-01-01-01-01\",\"codr\":\"4/5\",\"data\":\"YOeNkAAg1wQAYjm/pg==\",\"datr\":\"SF7BW125\",\"deveui\":\"39-31-37-33-5b-37-67-19\",\"freq\":868.29999999999995,\"gweui\":\"00-80-00-00-a0-00-24-6d\",\"id\":0,\"ipol\":true,\"mhdr\":\"60e78d900020d704\",\"mic\":\"6239bfa6\",\"modu\":\"LORA\",\"ncrc\":true,\"opts\":\"\",\"port\":0,\"powe\":11,\"rfch\":0,\"seqn\":1239,\"size\":13,\"tmst\":3491353235,\"twnd\":1}",
"fromip": "127.0.0.1:35068",
"ip": "127.0.0.1",
"port": 35068,
"_msgid": "193b00a8.e6c4ff"
}
var res = response.payload.substring(
response.payload.lastIndexOf("data") + -1,
response.payload.lastIndexOf("==") + 3
);
console.log(res)

How can I remove completed tasks in toDo App Javascript

I don't have idea how can i deleted all completed tasks from my json file and my app view:
json:
{
"list": [
{
"name": "Cleaning",
"desc": "by me",
"date": "11-3-2018 13:38",
"active": "false",
"id": 1
},
{
"name": "Wash the dishes",
"desc": "by me",
"date": "11-3-2018 23:11",
"active": "true",
"id": 2
},
{
"name": "Training",
"desc": "go with bro",
"date": "15-1-2016 23:41",
"active": "false",
"id": 3
}
]
}
I would like to deleted all tasks - active: false by one click button.
I have to use XMLHttpRequest.
You can loop through your JSON variable then have a condition on checking the active key. If its true then remove it. You can use splice to remove elements from an array. Then send it to your server side or etc.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
You will need to go server side to change the content of files, which I think you want to do.
Using JS and PHP you would get something like:
For the JS:
$("#yourButtonId").on('click', function(){
//Get the JSON file
var request = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var jsonObj = JSON.parse(this.responseText);
//Go over all tasks and remove if active is set to false
for (var i = 0; i < jsonObj.length; i++) {
if(jsonObj.list[i].active == "false"){
delete jsonObj.list[i];
};
}
//Send the updated json file as string to PHP
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "yourphpfile.php");
xmlhttp.send(JSON.stringify(jsonObj));
}
}
request.open("GET", "urlToJson.json", false);
request.setRequestHeader("Content-type", "application/json")
request.send(null);
});
For the PHP:
//Get your updated json string
$theJson = $GET['jsonObj'];
//Write the updated json string to the file
$myfile = fopen("urlToJson.json", "w") or die("Unable to open file!");
fwrite($myfile, json_encode($theJson));
fclose($myfile);
Try this :
var jsonObj = {
"list": [{
"name": "Cleaning",
"desc": "by me",
"date": "11-3-2018 13:38",
"active": "false",
"id": 1
},
{
"name": "Wash the dishes",
"desc": "by me",
"date": "11-3-2018 23:11",
"active": "true",
"id": 2
},
{
"name": "Training",
"desc": "go with bro",
"date": "15-1-2016 23:41",
"active": "false",
"id": 3
}
]
};
function removeCompletedTask() {
var resJson = jsonObj.list.filter(item => item.active == "true");
console.log(resJson);
}
<input type="button" value="Remove" onClick="removeCompletedTask()"/>
I use only json server (without php file)
If I want to delete single task I do this code
function deleteTask(task) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url + "/" + task.dataset.id, true);
xhr.onload = function() {
var json = JSON.parse(xhr.responseText)
if (xhr.readyState == 4 && xhr.status == 200) {
task.parentNode.parentNode.removeChild(task.parentNode);
}
}
xhr.send(null);
}
I did checkbox to change active my tasks and i would like to delete all of them i try something like this:
function clearTasksCompleted(task) {
var taskCompleted = task.parentElement.parentElement.querySelectorAll('li');
var completed = [];
for(let i =0; i<taskCompleted.length; i++){
if(taskCompleted[i].querySelector('.checkbox').checked)
{
completed.push(taskCompleted[i]);
}
}
for (let i=0; i<completed.length; i++) {
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url + "/" + completed[i].dataset.id, true);
xhr.onload = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
completed[i].parentNode.removeChild(completed[i])
}
}
xhr.send(null);}}
`
and this deleted tasks from json but dont render my page automatically, only after preload i don't see completed tasks

getting JSON data from REST API by javascript displays partial data

I am trying to get data from alchemynewsapi through javascript. The sample data i receive is:
{
"status": "OK",
"totalTransactions": "68",
"result": {
"docs": [
{
"id": "ODU1MjM4MjM0NnwxNDQ5MDk0Mzgy",
"source": {
"enriched": {
"url": {
"title": "North Scituate observatory hosts workshop on telescopes",
"url": "http://www.providencejournal.com/article/20151201/entertainmentlife/151209982"
}
}
},
{
"id": "ODEzMzYxODU5MHwxNDQ5MDYyMjM0",
"source": {
"enriched": {
"url": {
"title": "Mob Programming Workshop",
"url": "https://www.eventbrite.com/e/mob-programming-workshop-tickets-19710798529"
}
}
},
"timestamp": 1449062234
}
],
"next": "MzY5OTc0NjQzNzI2MjMxNzM2N3xPREU1TnpnNU9EWXhPSHd4TkRRNU1EWTNPVFE1",
"status": "OK"
}
}
I am trying the following for retrieving title and url fields of the data:
var jsonData=getJSON('http://urlofapi').then(function(data) {
for(var i=0; i<data.result.docs.length; i++)
{
result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field
}
}, function(status) { //error detection....
alert('Something went wrong.');
});
getJSON is a function i have created :
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
But it only displays me the last title of the data i.e here the "Mob..."
What needs to be done to retrieve all the titles if there are 100's of items?
It's quite normal, your code has:
result.innerText = data.result.docs[i].source.enriched.url.title; //for retrieving the title field
Which means you constantly replace the contents of resultwith a new title, so at the end, you display the last one.
You need to concatenate the data somehow, or use console.log if you're just trying to see the results before doing something more with them.

Categories

Resources