Backbone - Collection not populating from JSON - javascript

I'm trying to populate a Backbone collection from the JSON that spotify API return me. However, after I try populating the collection I'm getting this with a console.log() :
playlistSpotify child {length: 1, models: Array[1], _byId: Object}. But my collection should contain 3 objects (3 objects in the JSON returned).
Any ideas of what's going on?
JS:
Model :
module.exports = Backbone.Model.extend({
defaults: {
id: null,
selected : false,
name: null
},
initialize: function() {
}
});
Collection :
module.exports = Backbone.Collection.extend({
model : Playlist,
initialize: function() {
}
});
View (Just the function that load the JSON):
loadSpotifyPlaylists : function() {
var that = this;
$.ajax({
url: 'https://api.spotify.com/v1/users/'+ this.user.get('spotifyId') +'/playlists',
headers: {
'Authorization': 'Bearer ' + this.user.get('spotifyToken')
},
success: function(response) {
var playlistCollection = new Playlists2({ collection : JSON.stringify(response.items) });
var playlistView = new PlaylistSpotifyView({ collection : playlistCollection });
that.$playListsSpotify.append(playlistView.render().el);
}
});
},
The JSON Spotify return me (I volontary remove one item to make it shorter) :
{
"href": "https://api.spotify.com/v1/users/loco/playlists?offset=0&limit=20",
"items": [
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/loco/playlist/6MpEay73SWJzyJHGu5u6bK"
},
"href": "https://api.spotify.com/v1/users/loco/playlists/6MpEay73SWJzyJHGu5u6bK",
"id": "6MpEay73SWJzyJHGu5u6bK",
"images": [
{
"height": 640,
"url": "https://mosaic.scdn.co/640/dc8743ffb149138cfe29334147b835532dbee0ddf3320826…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 640
},
{
"height": 300,
"url": "https://mosaic.scdn.co/300/dc8743ffb149138cfe29334147b835532dbee0ddf3320826…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 300
},
{
"height": 60,
"url": "https://mosaic.scdn.co/60/dc8743ffb149138cfe29334147b835532dbee0ddf33208261…dc7e917657c7982eab6ed5126307c6c3a67e1a3fb78245a8477312eeaec1621a2849969219",
"width": 60
}
],
"name": "quizz musical",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/loco"
},
"href": "https://api.spotify.com/v1/users/loco",
"id": "loco",
"type": "user",
"uri": "spotify:user:loco"
},
"public": false,
"snapshot_id": "1OUgCAhN+ZsJo6whDez1kVA/R2DooVY4Rzw+Vij5HYHgz/PDFpjbUaiXz+fkapX7",
"tracks": {
"href": "https://api.spotify.com/v1/users/loco/playlists/6MpEay73SWJzyJHGu5u6bK/tracks",
"total": 64
},
"type": "playlist",
"uri": "spotify:user:loco:playlist:6MpEay73SWJzyJHGu5u6bK"
},
{
"collaborative": false,
"external_urls": {
"spotify": "http://open.spotify.com/user/loco/playlist/2KlAANyACpjJZmZfVGK0Mb"
},
"href": "https://api.spotify.com/v1/users/loco/playlists/2KlAANyACpjJZmZfVGK0Mb",
"id": "2KlAANyACpjJZmZfVGK0Mb",
"images": [
{
"height": 640,
"url": "https://i.scdn.co/image/24e6e9aac4ea49d92e260bb6875f4882c65c7f48",
"width": 640
}
],
"name": "Playlist2",
"owner": {
"external_urls": {
"spotify": "http://open.spotify.com/user/loco"
},
"href": "https://api.spotify.com/v1/users/loco",
"id": "loco",
"type": "user",
"uri": "spotify:user:loco"
},
"public": true,
"snapshot_id": "fqLltawhg+mMNV+nVEl5Rmj94uDI1kdbbzoZLPbs7uVtZclbYJqyEtIAvIacExVe",
"tracks": {
"href": "https://api.spotify.com/v1/users/loco/playlists/2KlAANyACpjJZmZfVGK0Mb/tracks",
"total": 1
},
"type": "playlist",
"uri": "spotify:user:loco:playlist:2KlAANyACpjJZmZfVGK0Mb"
}
],
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total": 3
}
After some exploration I see this thing when I console.log the collection. I can't really understand what's happened.
Any help would be appreciated ! :)

You have a wrong creation of the instances. Change it to the next:
var playlistCollection = new Playlists2(response.items);
var playlistView = new PlaylistSpotifyView({ model : playlistCollection });
To initialize collection, you need just simply pass an array of objects as the argument to the constructor of collection

Related

How to upload file and array of objects with formdata in javascript to pass formdata in ajax

The output data are like the following params:
const treatementListe = {
"id": 0,
"date": "2021-10-22T09:41:19.678Z",
"selectedTraitements": "Injection1",
"selectedZones": "Face",
"traitementNote": "Careful",
"files": [
{
"upload": {
"progress": 100,
"total": 20261,
"bytesSent": 20261,
"filename": "1617826401810IMG-20210211-WA0002.jpg",
"chunked": false,
"totalChunkCount": 1
},
"status": "success",
"previewElement": {},
"previewTemplate": {},
...etc
}
]
},
{
"id": 1,
"date": "2021-10-22T09:41:19.678Z",
"selectedTraitements": "Injection2",
"selectedZones": "Ear",
"traitementNote": "Careful",
"files": [
{
"upload":{
"progress": 100,
"total": 20261,
"bytesSent": 20261,
"filename": "1617826401810IMG-20210211-WA0002.jpg",
"chunked": false,
"totalChunkCount": 1
},
"status": "success",
"previewElement": {},
"previewTemplate": {},
...etc
}
]
}

How do I parse the realtor api data to show property data (Realtor API/Rapid)?

’m trying to parse the response data to view property data. However, I searched through all the properties in the response data but none seemed to hold property data.
For anybody who isn’t familiar with realtor API this is the site I’m talking about. The data shows the exact way I want to receive mine
https://rapidapi.com/apidojo/api/realtor/endpoints
fetch("https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=New%20York%20City&state_code=NY&limit=200&offset=0", {
"method": "GET",
"headers": {
"x-rapidapi-host": "realtor.p.rapidapi.com",
"x-rapidapi-key": "e5b0286ea4msh1d616284115d5efp16cadcjsn0392ca0398ac"
}
})
.then(response => {
console.log(response.json());
})
.catch(err => {
console.log(err);
});
I was able to use Postman and test this endpoint and found that you likely need to be looking for the properties array and loop through the objects and sub-arrays/objects contained in each parent object of the properties array to get to the details about each property.
Inside of this array are objects that contain the address, latitude, longitude, etc.
I would recommend using Postman if you are not already, doing a GET request when doing so and using the same headers. You should see the same. Using Postman is a great way to test endpoints!
Here is an example of the data that is returned from the results inside of the properties array when hitting your endpoint with a GET request:
"properties": [
...
...
{
"property_id": "R3188507190",
"listing_id": "612930061",
"prop_type": "apartment",
"list_date": "2018-08-20T17:22:00.000Z",
"last_update": "2020-08-25T08:17:00.000Z",
"year_built": 2018,
"listing_status": "active",
"beds": 0,
"prop_status": "for_rent",
"address": {
"city": "Arverne",
"country": "USA",
"county": "Queens",
"lat": 40.589922,
"line": "190 Beach 69th St",
"postal_code": "11692",
"state_code": "NY",
"state": "New York",
"time_zone": "America/New_York",
"neighborhood_name": "Rockaway Peninsula",
"neighborhoods": [
{
"id": "8c06e34c-3044-5621-aea4-b59d9ddde719",
"level": "macro_neighborhood",
"name": "Rockaway Peninsula"
}
],
"lon": -73.79765
},
"client_display_flags": {
"presentation_status": "for_rent",
"is_showcase": true,
"lead_form_phone_required": true,
"price_change": 0,
"has_specials": false,
"is_mls_rental": false,
"is_rental_community": true,
"is_rental_unit": false,
"is_co_star": true,
"is_apartmentlist": false,
"suppress_map_pin": false,
"suppress_phone_call_lead_event": true,
"price_reduced": false,
"allows_cats": true,
"allows_dogs": true,
"allows_dogs_small": true,
"allows_dogs_large": true
},
"agents": [
{
"primary": true
}
],
"lead_forms": {
"form": {
"name": {
"required": true,
"minimum_character_count": 1
},
"email": {
"required": true,
"minimum_character_count": 5
},
"move_in_date": {
"required": true,
"default_date": "2020-09-01T12:00:00Z",
"minimum_days_from_today": 1,
"maximum_days_from_today": 180
},
"phone": {
"required": true,
"minimum_character_count": 10,
"maximum_character_count": 11
},
"message": {
"required": false,
"minimum_character_count": 0
},
"show": false
},
"show_agent": false,
"show_broker": false,
"show_provider": false,
"show_management": false
},
"lot_size": {
"size": 0,
"units": "sqft"
},
"building_size": {
"units": "sqft"
},
"rdc_web_url": "https://www.realtor.com/realestateandhomes-detail/190-Beach-69th-St_Arverne_NY_11692_M31885-07190",
"rdc_app_url": "move-rdc://www.realtor.com/realestateandhomes-detail/190-Beach-69th-St_Arverne_NY_11692_M31885-07190",
"community": {
"baths_max": 1,
"baths_min": 1,
"beds_max": 1,
"beds_min": 1,
"contact_number": "(844) 454-2289",
"id": 1839240,
"name": "The Tides At Arverne By The Sea",
"price_max": 2195,
"price_min": 2195,
"source_id": "46dfexj",
"sqft_max": 659,
"sqft_min": 659
},
"data_source_name": "co-star",
"source": "community",
"page_no": 1,
"rank": 1,
"list_tracking": "type|property|data|prop_id|3188507190|list_id|612930061|comm_id|1839240|page|rank|data_source|co-star|property_status|product_code|advantage_code^1|1|3K2|E8|0^^$0|1|2|$3|4|5|6|7|8|9|G|A|H|B|C|D|I|E|J|F|K]]",
"photo_count": 19,
"photos": [
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f75218736o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3178227471o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3306091863o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1799178643o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f884518299o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1142482343o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f624998745o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3641852832o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2581754924o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f1976580515o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f586291969o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2803556443o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3294921843o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f852583007o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f4164216811o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f3902720508o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f850731407o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f2027588413o.jpg"
},
{
"href": "https://ar.rdcpix.com/610e208fe79b9533c5e103166312b312c-f805760224o.jpg"
}
]
},
...
...
]
If the response is not returning the data you expect then it could be that the format of your fetch GET request code is not quite right.
EDIT: In fact, that is exactly the problem I do believe. So, it should probably work if you try to structure your fetch similarly to this:
let url = 'https://realtor.p.rapidapi.com/properties/v2/list-for-rent?sort=relevance&city=New%20York%20City&state_code=NY&limit=200&offset=0';
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-rapidapi-host': 'realtor.p.rapidapi.com',
'x-rapidapi-key': 'e5b0286ea4msh1d616284115d5efp16cadcjsn0392ca0398ac'
}})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});

how to get particular key value from all the objects in a AJAX call

here is the code ,i just want to grab "url" key and its value and store it in a variable
i have tried several ways to segregate the key named url you can see that in my commented code
$.ajax({
type: 'GET',
url: "url",
// data: data,
// async: false,
beforeSend: function(xhr) {
if (xhr && xhr.overrideMimeType) {
xhr.overrideMimeType('application/json;charset=utf-8');
}
},
dataType: 'json',
success: function(res) {
// console.log(res);
// re=JSON.stringify(res);
re = $.parseJSON(res)
console.log(re['url'])
// console.log(re)
// console.log(re["url"])
// for(var url in re) {
// var value = objects[key];
// }
// console.log(Object.values('url'));
// ok=Object.keys(re).map(key => re[url])
// console.log(ok)
// console.log(re)
// $.each(re, function(key, value){
// console.log(key + value);
// });
// console.log(re[url])
// const seg = re.find(item => item.key === "url");
// const result=seg
// console.log(result)
// alert(res);
}
});
You need to resolve CORS issues with your Django backend to get the response correctly.
I see the response is of the following structure:
{
"count": 51,
"next": "http://scrapsh.herokuapp.com/api/post/?page=2",
"previous": null,
"results": [
{
"id": 1,
"title": "asdas",
"rate": 1,
"author": "madhumani",
"content": "asdad",
"review": null,
"url": null
},
{
"id": 2,
"title": "okau",
"rate": 1,
"author": "madhumani",
"content": "asdasd",
"review": null,
"url": null
},
{
"id": 3,
"title": "DASS",
"rate": 1,
"author": "madhumani",
"content": "sdfsdfs",
"review": null,
"url": null
},
...
]
}
To get the url you can simply use .map on the results array:
let response = {
"count": 51,
"next": "http://scrapsh.herokuapp.com/api/post/?page=2",
"previous": null,
"results": [{
"id": 1,
"title": "asdas",
"rate": 1,
"author": "madhumani",
"content": "asdad",
"review": null,
"url": "www.a.com"
},
{
"id": 2,
"title": "okau",
"rate": 1,
"author": "madhumani",
"content": "asdasd",
"review": null,
"url": "www.b.com"
},
{
"id": 3,
"title": "DASS",
"rate": 1,
"author": "madhumani",
"content": "sdfsdfs",
"review": null,
"url": "www.c.com"
}
]
}
console.log(response.results.map(item => {
return {
"url": item.url
}
}))

JSON append response with attribute from link

I have and API endpoint in Zapier where I am calling all approved leave requests from a payroll system. as data.
const options = {
url: 'https://api.somepayroll.com/api/v1/leaves/requests',
method: 'GET',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${bundle.authData.access_token}`,
'X-CLIENT-SECRET': bundle.authData.client_secret,
'X-CLIENT-ID': bundle.authData.client_id,
'X-STATUS': bundle.inputData.status
},
params: {
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
// You can do any parsing you need for results here before returning them
return results.content;
});
That gets me the following response:
[
{
"employeeId": "1",
"requestId": 5487,
"hours": 8,
"leaveFromDate": "19-Feb-2020",
"leaveToDate": "19-Feb-2020",
"reason": "Birthday Party",
"status": "Pending",
"payElement": "Annual Leave",
"leaveBalanceType": {
"leaveType": "Annual",
"name": "Annual Leave",
"unit": "hours",
"organisationSpecific": false
},
"payElementId": 50,
"daysConsumed": 0,
"daysCurrent": 0,
"daysRemaining": 0,
"quantityConsumed": 0,
"quantityCurrent": 0,
"quantityRemaining": 8,
"additionalApprovalAcquired": false,
"leaveInDays": false,
"links": [
{
"rel": "self",
"href": "https://api.somepayroll.com/api/v1/leaves/requests/5487"
},
{
"rel": "employee",
"href": "https://api.somepayroll.com/api/v1/employees/1"
},
{
"rel": "payelement",
"href": "https://api.somepayroll.com/api/v1/payelements/AL"
}
],
"id": "5487"
},
{
"employeeId": "1",
"requestId": 5551,
"hours": 8,
"leaveFromDate": "23-Jan-2020",
"leaveToDate": "23-Jan-2020",
"reason": "Camping",
"status": "Pending",
"payElement": "Annual Leave",
"leaveBalanceType": {
"leaveType": "Annual",
"name": "Annual Leave",
"unit": "hours",
"organisationSpecific": false
},
"payElementId": 50,
"daysConsumed": 0,
"daysCurrent": 0,
"daysRemaining": 0,
"quantityConsumed": 0,
"quantityCurrent": 0,
"quantityRemaining": 8,
"additionalApprovalAcquired": false,
"leaveInDays": false,
"links": [
{
"rel": "self",
"href": "https://api.somepayroll.com/api/v1/leaves/requests/5551"
},
{
"rel": "employee",
"href": "https://api.somepayroll.com/api/v1/employees/1"
},
{
"rel": "payelement",
"href": "https://api.somepayroll.com/api/v1/payelements/AL"
}
],
"id": "5551"
}
]
What I am trying to do is also grab the name of the employee from the link in the response https://api.somepayroll.com/api/v1/employees/1 since it is only giving me the ID number. Is is possible to cross link data like that and match on employeeID and get the data called firstName to be part of this result?
it should handle by back-end however you can call link from response and get extra data,

New to node.js here. How do I properly get the JSON from the top of a subreddit?

I am trying to call a get on this api url here: http://www.reddit.com/r/reddevils/top.json?sort=top&t=day&limit=1
and all I am trying to do is grab the permalink data, which is an element inside of an object called 'data' which is nested in another object called 'data'. I need the permalink data, so, I can export it and use it in another file.
I am trying to do this on node.js, how would I go about doing this? I have attempted to use the http, express, and ajax-request packages. I feel like I am on the right path, but it may be just a matter of proper syntax.
This is what I have right now. I was just trying to print out the JSON object onto my console to see if I am on the right path:
var request = require('ajax-request');
var http = require('http');
var url = "http://www.reddit.com/r/reddevils/top.json?sort=top&t=day&limit=1";
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var redditResponse = JSON.parse(body);
console.log("Got a response: ", redditResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
Thanks
When formatted, your data looks like this:
{
"kind": "Listing",
"data": {
"modhash": "fop7jgfq8z07efe8b23281496fdcd30eae5038b50d6b9811d2",
"children": [{
"kind": "t3",
"data": {
"contest_mode": false,
"subreddit_name_prefixed": "r/reddevils",
"banned_by": null,
"media_embed": {},
"thumbnail_width": 140,
"subreddit": "reddevils",
"selftext_html": null,
"selftext": "",
"likes": null,
"suggested_sort": null,
"user_reports": [],
"secure_media": null,
"link_flair_text": "TIER 0",
"id": "6jqxwx",
"view_count": null,
"secure_media_embed": {},
"clicked": false,
"report_reasons": null,
"author": "SuperShadowJr",
"saved": false,
"mod_reports": [],
"name": "t3_6jqxwx",
"score": 792,
"approved_by": null,
"over_18": false,
"domain": "instagram.com",
"hidden": false,
"preview": {
"images": [{
"source": {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?s=5fe73832273b3e88324a6da17fa55fae",
"width": 640,
"height": 640
},
"resolutions": [{
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=108&s=b668298ccd3a69304ab23c5aef1b6d77",
"width": 108,
"height": 108
}, {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=216&s=706a70a275e20973e8ce772f362db87f",
"width": 216,
"height": 216
}, {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=320&s=42c33880cf1a0a1c14e814de5469a1a1",
"width": 320,
"height": 320
}, {
"url": "https://i.redditmedia.com/qKDgoT2EDbwYbozYQO23nDisAj6yd9I2XwdWKLw-QNQ.jpg?fit=crop&crop=faces%2Centropy&arh=2&w=640&s=783b2011d7523d9c84450293eef9d6c0",
"width": 640,
"height": 640
}],
"variants": {},
"id": "TNO0lZhaqwUX-vbTYG6y0bI6hZhhgQJWTgm_OVk7b2E"
}],
"enabled": false
},
"thumbnail": "https://a.thumbs.redditmedia.com/8U2J6sELZ1AIGDsReUz-v10X3qyFG49TBH0XrjXAMc8.jpg",
"subreddit_id": "t5_2rxse",
"edited": false,
"link_flair_css_class": "black",
"author_flair_css_class": null,
"gilded": 0,
"downs": 0,
"brand_safe": true,
"archived": false,
"removal_reason": null,
"post_hint": "link",
"can_gild": true,
"thumbnail_height": 140,
"hide_score": false,
"spoiler": false,
"permalink": "/r/reddevils/comments/6jqxwx/fabinhos_girlfriendwife_likes_ig_picture_of/",
"num_reports": null,
"locked": false,
"stickied": false,
"created": 1498574067.0,
"url": "https://www.instagram.com/p/BV0dLySgy82/",
"author_flair_text": null,
"quarantine": false,
"title": "Fabinho's girlfriend/wife likes IG picture of Fabinho in MUFC kit with the caption \"Could we see this man in the PL?\"",
"created_utc": 1498545267.0,
"distinguished": null,
"media": null,
"num_comments": 79,
"is_self": false,
"visited": false,
"subreddit_type": "public",
"is_video": false,
"ups": 792
}
}],
"after": "t3_6jqxwx",
"before": null
}
}
So, you can use:
redditResponse.data.children[0].data.permalink
Working demo: https://jsfiddle.net/jfriend00/nkpchrk0/
If you want all the children, then you need to iterate i in:
redditResponse.data.children[i].data.permalink
to fetch each one.
Or, to get them all at once into their own array, you could do this:
let permaLinks = redditResponse.data.children.map(function(child) {
return child.data.permalink;
});

Categories

Resources