getting JSON data from REST API by javascript displays partial data - javascript

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.

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

Looping through items in an object for google sheets

I am trying to loop through an array that is part of a JSON object from a page speed insights call to add all of the unused javascript Urls to a google sheet using the script editor.
Here is an example of the JSON object:
"audits": {
"unused-javascript": {
"id": "unused-javascript",
"title": "Remove unused JavaScript",
"description": "Remove unused JavaScript to reduce bytes consumed by network activity. [Learn more](https://web.dev/unused-javascript/).",
"score": 0.43,
"scoreDisplayMode": "numeric",
"numericValue": 1350,
"numericUnit": "millisecond",
"displayValue": "Potential savings of 231 KiB",
"details": {
"type": "opportunity",
"headings": [
{
"key": "url",
"valueType": "url",
"subItemsHeading": {
"key": "source",
"valueType": "code"
},
"label": "URL"
},
{
"key": "totalBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceBytes"
},
"label": "Transfer Size"
},
{
"key": "wastedBytes",
"valueType": "bytes",
"subItemsHeading": {
"key": "sourceWastedBytes"
},
"label": "Potential Savings"
}
],
"items": [
{
"url": "https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable",
"totalBytes": 140229,
"wastedBytes": 108197,
"wastedPercent": 77.15757011763822
},
{
"url": "https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js",
"totalBytes": 306716,
"wastedBytes": 106243,
"wastedPercent": 34.63892414884589
},
{
"url": "https://www.googletagmanager.com/gtm.js?id=GTM-KZ",
"totalBytes": 127214,
"wastedBytes": 21845,
"wastedPercent": 17.17151000374831
}
],
"overallSavingsMs": 1350,
"overallSavingsBytes": 236285
}
},
I am attempting to loop through the "items" array within the "unused-javascript" object and get all of the urls to show in google sheets.
Here is the code I have within the script editor. When I run this, only one URL shows on the sheet. However, I am trying to get all of the URLs added to the sheet.
function pageSpeed(Url) {
var key = "AIzaSyAyHY";
var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key;
var array = [];
if (key == "YOUR_API_KEY")
return "Please enter your API key to the script";
var response = UrlFetchApp.fetch(serviceUrl);
if (response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ((content != null) && (content["lighthouseResult"] != null)) {
if (content["captchaResult"]) {
var timetointeractive = content["lighthouseResult"]["audits"]["interactive"]["displayValue"].slice(0, -2);
var firstcontentfulpaint = content["lighthouseResult"]["audits"]["first-contentful-paint"]["displayValue"].slice(0, -2);
var firstmeaningfulpaint = content["lighthouseResult"]["audits"]["first-meaningful-paint"]["displayValue"].slice(0, -2);
var speedindex = content["lighthouseResult"]["audits"]["speed-index"]["displayValue"].slice(0, -2);
var unusedJs = content["lighthouseResult"]["audits"]["unused-javascript"]["details"]["items"];
for (var i = 0; i < unusedJs.items.length; i++) {
var unusedUrl;
unusedUrl = unusedJs[i]["url"]
}
}
else {
var timetointeractive = "An error occured";
var firstcontentfulpaint = "An error occured";
var firstmeaningfulpaint = "An error occured";
var speedindex = "An error occured";
var unusedJs = "An error occured";
}
}
var currentDate = new Date().toJSON().slice(0, 10).replace(/-/g, '/');
array.push([timetointeractive, firstcontentfulpaint, firstmeaningfulpaint, speedindex, currentDate, "complete", unusedUrl]);
Utilities.sleep(1000);
return array;
}
}
Any and all help is appreciated!
You're on the right track.
Take a look below at my usage of Array.prototype.map. That's the simpler route.
Your for loop would work just as well IF you declared unusedUrl outside of (ie. before) the loop AND pushed to an existing array. As it is, there's an issue of scope, so unusedUrl is redeclared on every iteration, meaning you'll only assign the last iteration's value to unusedUrl.
Both solutions are below.
Using map
var content = {
lighthouseResult: {
audits: {
'unused-javascript': {
// Other stuff
details: {
// Other stuff
items: [
{
url:
'https://connect.facebook.net/signals/config/1926350194273730?v=2.9.2=stable',
totalBytes: 140229,
wastedBytes: 108197,
wastedPercent: 77.15757011763822,
},
{
url:
'https://static.example.com/domain.us.modern.bundle.a02fef045566caf5d464.js',
totalBytes: 306716,
wastedBytes: 106243,
wastedPercent: 34.63892414884589,
},
{
url: 'https://www.googletagmanager.com/gtm.js?id=GTM-KZ',
totalBytes: 127214,
wastedBytes: 21845,
wastedPercent: 17.17151000374831,
},
],
overallSavingsMs: 1350,
overallSavingsBytes: 236285,
},
},
},
},
}
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = items.map(item => item.url) // OR, using es6, items.map(({ url }) => url)
console.log(unusedUrls)
Using for
var items = content.lighthouseResult.audits['unused-javascript'].details.items
var unusedUrls = []
for (var i = 0; i < items.length; i++) {
unusedUrls.push(items[i]['url'])
}

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.

Categories

Resources