Looping over Json Array In JS - javascript

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 => .....);
}

Related

I want to put the first done transition date in a custom field of already done issues from JIRA using Jira api and scripts

Assume that this is the changelog of a Jira issue
{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "72194",
"self": "https://jira.instance.net/rest/api/2/issue/72194",
"key": "TII-627",
"changelog": {
"startAt": 0,
"maxResults": 1,
"total": 1,
"histories": [
{
"id": "12345",
"author": {
"self": "https://jira.instance.net/rest/api/2/user?accountId=xxxxxxxxxxx",
"accountId": "xxxxxxxxxxxx",
"emailAddress": "xxx#yy.com",
"avatarUrls": {},
"displayName": "John Doe",
"active": true,
"timeZone": "Anywhere",
"accountType": "atlassian"
},
"created": "2023-02-07T10:30:02.897+0530",
"items": [
{
"field": "status",
"fieldtype": "jira",
"fieldId": "status",
"from": "10000",
"fromString": "To Do",
"to": "5",
"toString": "Resolved"
}
]
}
]
},
"fields": {
"status": {
"self": "https://jira.instance.net/rest/api/2/status/5",
"description": "A resolution has been taken, and it is awaiting verification by reporter. From here issues are either reopened, or are closed.",
"iconUrl": "something",
"name": "Resolved",
"id": "5",
"statusCategory": {
"self": "https://jira.instance.net/rest/api/2/statuscategory/3",
"id": 3,
"key": "done",
"colorName": "green",
"name": "Done"
}
}
}
}
In this changelog you can see that the issue with "key": "TII-627" was first transition to done statuscategory aka Resolved status on "created": "2023-02-07T10:30:02.897+0530"
I want to get this first transition to done and print it in a table for all issues in the project like this
issue_key, first_resolved_at
for the eg. above it would look like this
TII-627, 2023-02-07T10:30:02.897+0530
I have tried using the following ruby script but I am getting the first resolved date empty please let me know what can I do
require 'jira-ruby'
# JIRA API credentials
jira_username = '<your-jira-username>'
jira_token = '<your-jira-api-token>'
jira_domain = '<your-jira-instance-domain>'
# initialize client
options = {
:username => jira_username,
:password => jira_token,
:site => "https://#{jira_domain}",
:context_path => '',
:auth_type => :basic
}
client = JIRA::Client.new(options)
# Define the issue key as a command line argument
issue_key = ARGV[0]
# Log the start time of the script
start_time = Time.now
puts "Start time: #{start_time}"
# Get the issue information
begin
issue = client.Issue.find(issue_key)
issue_status_category = issue.fields['status']['statusCategory']['name']
# If issue has already reached done status, retrieve the transitions
if issue_status_category == 'Done'
transitions = issue.transitions
first_resolved_at = nil
last_resolved_at = nil
# Retrieve the first and last resolved dates
transitions.each do |transition|
transition_status_category = transition['to']['statusCategory']['name']
if transition_status_category == 'Done'
transition_created_at = DateTime.parse(transition['created'])
if first_resolved_at.nil?
first_resolved_at = transition_created_at
end
last_resolved_at = transition_created_at
end
end
# Print the results
puts "Issue Key: #{issue.key}"
puts "First Resolved At: #{first_resolved_at}"
puts "Last Resolved At: #{last_resolved_at}"
else
puts "Issue has not yet reached Done status."
end
rescue Exception => e
# Log the error
puts "Error: #{e}"
end
# Log the end time of the script
end_time = Time.now
puts "End time: #{end_time}"
I am closing the question. I was able to figure out another way using JS
const axios = require("axios");
​
async function getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues) {
for (const issue of issues) {
let changelogs = [];
let url = jiraDomain + "/rest/api/2/issue/" + issue + "?expand=changelog";
let response = await axios({
method: "get",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
}
});
let data = response.data;
let changelog = data.changelog.histories;
if (!Array.isArray(changelog)) {
changelog = [changelog];
}
for (const history of changelog) {
let items = history.items;
for (const item of items) {
if (item.field === "status" && (item.toString === "Resolved" || item.toString === "Invalid")) {
let firstResolvedAt = history.created;
changelogs.push({
issue_key: issue,
first_resolved_at: firstResolvedAt
});
break;
}
}
}
let earliestDate = new Date(Math.min.apply(null, changelogs.map(function(c) {
return new Date(c.first_resolved_at);
})));
let formattedDate = earliestDate.toISOString();
url = jiraDomain + "/rest/api/2/issue/" + issue;
let body = {
fields: {
customfield_xxx: formattedDate
}
};
response = await axios({
method: "put",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
},
data: body
});
if (response.status === 200 || response.status === 204) {
console.log("Successfully updated first resolved date for issue " + issue);
} else {
console.error(response);
}
}
}
​
const jiraUsername = 'xxx';
const jiraToken = "xxx";
const jiraDomain = "https://xxx";
const issues = ['xxx-1'];
​
getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues)
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});

json to javascript variable zendesk

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>

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

Issue parsing JSON arrays (unexpected end / undefined xhr.responseText)

{
"requirements": [
{
"name": {
"required":true,
"type":"string",
"length":{"min":3}
}
},
{
"phone": {
"type":"number",
"required":true
}
}
],
"people": [
{
"id":1,
"name":"Jim",
"Phone":0123456789
},
{
"id":2,
"name":"Jack",
"Phone":4738383838
}
]
}
function request (method, url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200)
val = JSON.parse(xhr.responseText);
console.log (val.people[1]);
}
xhr.open(method, url, true);
xhr.send(null);
}
I'm having issues parsing this JSON. Before it was invalid, but I fixed it. Now, it comes up as undefined or it tells me that there was an unexpected end to the JSON. I'm not 100% sure if val.people[1] is the correct way to do this.
The parser is stumbling on the leading zero of the following integer: 0123456789.
It's treating it as an octal number.

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