Backbone JS: how to parse JSON response with dynamic named objects - javascript

I'm trying to parse the following JSON response to a Backbone.Collection:
{
"16": {
"_id": "16",
"lastname": ...,
...
},
"17": {
"_id": "17",
"lastname": ...,
...
},
...
},
"39": {
"_id": "39"
"lastname": ...,
...
}
}
How could one parse the set of name/value pairs ("_id", "lastname", ...)?

you need to return an array in order to parse it to a collection.
so in your parse function:
parse: function (response) {
return _.map(response, function(obj) {
return obj;
});
}
make sure in your model, you have defined the correct idAttribute since you are using non-standard id name:
var YourModel = Backbone.Model.extend({
idAttribute: "_id"
});

Related

How do I select an adjacent value from a JSON array using map()?

I have some JSON as shown below...
var JSONobj = {
"headline":{
"localized":{
"en_US":"Doctor"
},
"preferredLocale":{
"country":"US",
"language":"en"
}
},
"identities":[
{
"access_token":"AQVUTBfbOs5JLsdfsdfH_W1aZ2N0PrbL0LhD5Y5-g",
"provider":"linkedin",
"user_id":"v57678565vf",
"connection":"linkedin",
"isSocial":true
},
{
"access_token":"AQVUTBsdfsdfsdfsdfwePrbL0LhD5Y5-g",
"provider":"facebook",
"user_id":"hshs8722",
"connection":"facebook",
"isSocial":true
}
],
"name":"John Bob"
};
Using JavaScript I need to go through each item in the "identities" array, find the item with a "connection" value of "facebook", and return the associated "access_token" value.
Note: This example has two items in the "identities" array, but in production there will a dynamic number of items. Sometimes more, sometimes less.
I have been trying to do it using map() as shown below, but I can't figure it out.
var access_token = JSONobj.identities.map(i=>i.connection);
console.log(access_token);
You can use Array.find to find the first object in identities that has a connection of "facebook", then extract the access_token from that object:
var JSONobj = {
"headline": {
"localized": {
"en_US": "Doctor"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"identities": [{
"access_token": "AQVUTBfbOs5JLsdfsdfH_W1aZ2N0PrbL0LhD5Y5-g",
"provider": "linkedin",
"user_id": "v57678565vf",
"connection": "linkedin",
"isSocial": true
},
{
"access_token": "AQVUTBsdfsdfsdfsdfwePrbL0LhD5Y5-g",
"provider": "facebook",
"user_id": "hshs8722",
"connection": "facebook",
"isSocial": true
}
],
"name": "John Bob"
};
var access_token = JSONobj.identities.find(o => o.connection == 'facebook').access_token;
console.log(access_token);
Note (as pointed out by #secan) that if it's possible that there might not be an identity with a connection of "facebook", it is safer to use:
(JSONobj.identities.find(i=>i.connection === 'facebook')||{}).access_token;
as this will return undefined rather than raising an error.
Another alternative in that situation (as pointed out by #pilchard) is to use optional chaining (although this requires a fairly recent browser for support):
JSONobj.identities.find(i=>i.connection === 'Facebook')?.access_token;
create a generala function wich accept identities array and required connection name,
you can use Array.find to go through connection array items
function getAccessToken(identitiesArr, connection) {
let identity = identitiesArr.find(e => e.connection == connection);
if (identity)
return identity.access_token;
return '';
}
var JSONobj = {
"headline": {
"localized": {
"en_US": "Doctor"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"identities": [{
"access_token": "AQVUTBfbOs5JLsdfsdfH_W1aZ2N0PrbL0LhD5Y5-g",
"provider": "linkedin",
"user_id": "v57678565vf",
"connection": "linkedin",
"isSocial": true
},
{
"access_token": "AQVUTBsdfsdfsdfsdfwePrbL0LhD5Y5-g",
"provider": "facebook",
"user_id": "hshs8722",
"connection": "facebook",
"isSocial": true
}
],
"name": "John Bob"
};
let token = getAccessToken(JSONobj.identities, "facebook");
console.log(token);

Underscore.js where() function issue with searching json objects

I have a json collection stored as {"books": [{...}, ... ]} in a file. "books" is a list of json objects where each is a book. For example:
{
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
}
I have a need to read the json using _.where, specifically search every item in the collection for the "identifier" value of "type": "ISBN_10". Then return the full json object aka {"items": [...]}.
Suppose req.params.id is the "identifier" value (i.e. 0984782850).
This piece of code is not working
var _ = require('underscore');
...
app.get('/api/books/:id', function(req, res) {
var book = _.where(booksData.books.items[0].volumeInfo.industryIdentifiers[0], {identifier: req.params.id});
res.json(book);
});
it is returning
TypeError: Cannot read property '0' of undefined at position 43
The file has valid json, I have tried
var book = _.where(booksData.books, {items[0].volumeInfo.industryIdentifiers[0].identifier: req.params.id});
which also does not work
There is always one item in "items" and the ISBN_10 identifier is the first item in "industryIdentifiers" hence items[0].volumeInfo.industryIdentifiers[0].identifier
What am I doing wrong?
*EDIT: I tried with industryIdentifiers, but response is [ ]
Don't use industryIdentifiers[1]. You want to search the entire industryIdentifiers array, not a single object.
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: req.params.id})[0];
You also need books[0], since books is also an array.
const booksData = {
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
};
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: "0984782850"})[0];
console.log(book);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

Removing attribute when writing file to JSON

I have requested data from an API which is returned in JSON format, then written to a JSON file stored on a web server. I am then displaying filtered contents from the stored JSON file to a webpage using Angular.js.
The NodeJS code I am using to write the the API response to a file is the following:
var doNotStringify = {
currentTarget: true,
delegateTarget: true,
originalEvent: true,
target: true,
toElement: true,
view : true,
count : true,
message : true,
error : true,
}
tl.employees.all(function(response){
fs.writeFile(file, JSON.stringify(response, function(key, value) {
var result = value;
if(doNotStringify.hasOwnProperty(key)) {
result = undefined;
}
return result;
}, 4));
});
This strips out all unneeded elements, apart from 'Data'. I can't strip out Data in the function above as it deletes the contents of the element. So the result is the following JSON file:
{
"Data": [{
"FirstName": "Test1",
"LastName": "User",
}, {
"FirstName": "user",
"LastName": "user",
}, {
"FirstName": "Ropbert",
"LastName": "Jones",
}, {
"FirstName": "Jim",
"LastName": "Morrison",
}]
}
When editing out the 'Data' element manually, it works find in HTML/Angular with the following:
<td>{{player.firstName}}</td>
However, when a new JSON file is written containing the 'Data' element, it breaks and isn't displayed on the web page.
So my Question:
Is there a way to exclude the 'Data' element from writing to a file using fs.writeFile and JSON.stringify?
Or, is there something I can do in Angular get around it?
If you just want to strip out the data part, You can just create another element with the contents.In Angular also, I think you can do that with your model. Here is an example(not angular specific):
var playerdata = {
"Data": [{
"FirstName": "Test1",
"LastName": "User",
}, {
"FirstName": "user",
"LastName": "user",
}, {
"FirstName": "Ropbert",
"LastName": "Jones",
}, {
"FirstName": "Jim",
"LastName": "Morrison",
}]
};
playerdata = playerdata["Data"];
console.log(playerdata);
playerdata.forEach(function(player){
console.log(player.FirstName);
})

Construct models from a Collection fetch in Backbone.js

I am using Backbone to retrieve data over a REST API. My code is as follows:
var PlayerModel = Backbone.Model.extend({});
var PlayersCollection = Backbone.Collection.extend({
url: "http://api.football-data.org/v1/teams/81/players",
model: PlayerModel
});
var catalons = new PlayersCollection();
catalons.fetch();
This is the JSON output I receive if I do a GET request in POSTMAN
{
"_links": {
"self": {
"href": "http://api.football-data.org/v1/teams/81/players"
},
"team": {
"href": "http://api.football-data.org/v1/teams/81"
}
},
"count": 24,
"players": [
{
"name": "Marc-André ter Stegen",
"position": "Keeper",
"jerseyNumber": 1,
"dateOfBirth": "1992-04-30",
"nationality": "Germany",
"contractUntil": "2019-06-30",
"marketValue": "15,000,000 €"
},
{
"name": "Claudio Bravo",
"position": "Keeper",
"jerseyNumber": 13,
"dateOfBirth": "1983-04-13",
"nationality": "Chile",
"contractUntil": "2018-06-30",
"marketValue": "15,000,000 €"
}
]
}
I am successfully able to receive data using fetch, the thing which I am unable to figure out is how do I parse the fetched data so that my collection catalons will contain nothing but only the players? i.e. similar to if I had set it up this way:
var catalons = new PlayersCollection(playerModelArray);
You can do this using Backbone's Collection parse method. You simply need to add a parse method to your PlayersCollection prototype definition:
var PlayersCollection = Backbone.Collection.extend({
url: "http://api.football-data.org/v1/teams/81/players",
model: PlayerModel,
parse: function (response) {
return response.players;
}
});

How to create a json-schema out of a json object

Given a browser debugger output of root.value with two properties in javascript
root.value
__proto__: {...}
firstname: "my name"
age: 25
I want to parse it to a JSON string including the type like below. Or literally convert the above json object to the format below.
{
"$schema": "http://json-schema.org/draft-04/schema",
"title": "Basic Info",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"age": {
"type": "number"
}
}
}
Does any one know how to do that in javascript or any framework I can use to achieve such?
Note: I did not created the JSON myself it's an output of another framework. So the types of the fields are unknown until runtime.
My main concern is to embed the json object values for
{ "properties": {
"firstName": {
"type": "string"
},
"age": {
"type": "number"
}
}
JSON.stringify(root.value);
will only return
{
{
"firstname":" my name"
},
{
"age": 25
}
}

Categories