I am using backbone's fetch method to retrieve a set of JSON from the server. Inside the fetch call, I have a success callback that correctly assigns attributes to a model for each object found.
var foo = assetCollection.fetch({
reset: true,
success: function(response){
var data = response.models[0].attributes.collection.items;
data.forEach(function(data){
assetCollection.add([
{src_href: data.data[0].value,
title: data.data[1].value
}
]);
});
console.log(assetCollection.models)
}
})
Right now I am working with a static set of JSON that has two objects. However, logging assetCollection.models returns three objects: the first is the initial server JSON response, while the next two are correctly parsed Backbone models.
How do I keep Backbone from adding the first object (the entire response from the server) to its set of models, and instead just add the two JSON objects that I am interested in?
The JSON object returned from the server is as follows:
{
"collection": {
"version": "1.0",
"items": [
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://cdn.images.express.co.uk/img/dynamic/36/590x/robin-williams-night-at-the-museum-498385.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Robin as Teddy Roosevelt"
}
]
},
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://b.vimeocdn.com/ts/164/830/164830426_640.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Mrs. Doubtfire"
}
]
}
]
}
}
You should modufy collection.
Probably you should change parse method:
yourCollection = Backbone.Collection.extend({
parse: function(data) {
return data.models[0].attributes.collection.items;
}
})
When you use fetch Backbone parse result and add all elements what you return in parse.
Related
I have an Apollo Client that I'm using to request data from a service. I want to use the data I get in response to create a network of nodes and links e.g.
// Response data:
{
"Team": [
{
"name": "Example Team",
"members": [
{ "name": "Bob" },
{ "name": "Alice" }
]
}
]
}
// Network data:
{
"nodes": [
{ "name": "Example Team" }
{ "name": "Bob" },
{ "name": "Alice" }
],
"links": [
{ "source": "Example Team", "target": "Bob" },
{ "source": "Example Team", "target": "Alice" }
]
}
Historically, before using GraphQL, I would have used Redux to store the munged API response in state and read from there.
Is it appropriate to take a GraphQL result from Apollo and immediately save it back to Apollo local state in a different form so it can be queried by components in that format?
The main problem I foresee is that I think I'd have to query to check if the data I want exists in local state, then make another query if it didn't. In a Redux-world this would be wrapped up inside my store which would then only make the request off to the API if it didn't have the data it needed which 'feels' much cleaner.
In my case this could be solved using Afterware in Apollo Client, see this answer for more information.
It would allow me to munge the returned data into the form I need, and return it in the response alongside the original data.
Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.
I'm using REST adapter, when I call App.Message.find() Ember.js makes call to the /messages to retrieve all messages and expect to see JSON structure like this:
{
"messages": [] // array contains objects
}
However API I have to work with response always with:
{
"data": [] // array contains objects
}
I only found the way1 to change namespace or URL for the API. How to tell REST adapter to look for data instead of messages property?
If this is not possible how to solve this problem? CTO said we can adapt API to use with REST adapter as we want, but from some reason we can't change this data property which will be on each response.
Assuming you are ok with writing your own adapter to deal with the difference, in the success callback you can simply modify the incoming name from "data" to your specific entity -in the case above "messages"
I do something like this to give you and idea of what if possible in a custom adapter
In the link below I highlighted the return line from my findMany
The json coming back from my REST api looks like
[
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
I need to transform this before ember-data gets it to look like this
{
"sessions": [
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
}
https://github.com/toranb/ember-data-django-rest-adapter/blob/master/packages/ember-data-django-rest-adapter/lib/adapter.js#L56-57
findMany: function(store, type, ids, parent) {
var json = {}
, adapter = this
, root = this.rootForType(type)
, plural = this.pluralize(root)
, ids = this.serializeIds(ids)
, url = this.buildFindManyUrlWithParent(store, type, ids, parent);
return this.ajax(url, "GET", {
data: {ids: ids}
}).then(function(pre_json) {
json[plural] = pre_json; //change the JSON before ember-data gets it
adapter.didFindMany(store, type, json);
}).then(null, rejectionHandler);
},
I am getting a JSON in response from server:
{
"width": "765",
"height": "990",
"srcPath": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_MERGED_/1273.pdf",
"coverPage": "",
"documents": [
{
"index": "1",
"text": "Archiving Microsoft® Office SharePoint® Server 2007 Data with the Hitachi Content Archive Platform and Hitachi Data Discovery for Microsoft SharePoint",
"type": "doc",
"id": "HDS_054227~201106290029",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_2.png"
}
]
},
{
"index": "11",
"text": "Brocade FCoE Enabling Server I/O Consolidation",
"type": "doc",
"id": "HDS_053732~201105261741",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_2.png"
}
]
}
]
}
And I want to get pagelocation of the children.
Can anyone tell me how to do this?
Hi
i also want to get indexes from this and then want to get pagelocations of that particular children. Can you tell me how would i do that?
And also when i when i am getting indexes array it is returning me ,, only and not the index nos.
I am using following code for that :
indexes=response.documents.map(function(e){ return e.children.index; })
Thanks & Regards
If you're interested in simply retrieving all the page locations, you can do it using filter:
var locations = [];
json.documents.forEach(function(e,i) {
e.children.forEach(function(e2,i2) {
locations.push(e2.pageLocation);
)}
});
// returns flat array like [item1,item2,item3,item4]
You can get an array of arrays using map:
var locations = [];
var locations = json.documents.map(function(e) {
return e.children.map(function(e2) {
return e2.pageLocation;
});
});
// returns 2-dimensional array like [[item1,item2],[item1,item2]]
Your json response is an appropriate javascript object So you can access all elements of the object like you do as in back end.
here, you have an array of object of the type documents and each document object has array of objects of the type children. so
syntax would be
myjson.documents[0].children[0].pagelocation
( = http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png)
will give you the very first page location..
and so on
I aam trying to GET an array from a JSON file using JQuery's ajax methods. Specifically, I want to make the ajax request on document load and use the acquired data in other functions.
Here is my code:
$(document).ready(function() {
getJSON();
clickEvents();
});
function getJSON() {
$.getJSON('goods.js', function(data) {
crazyFun(data.Goods);
addScores(data.karma);
});
}
}
function addScores(karma) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
function crazyFun(Goods) {
for (var i = 0; i < Goods.length; i++) {
var alpha= $('#template').clone();
alpha.removeAttr('id');
alpha.find('div.picture').attr('id', Goods[i].picture);
alpha.find('h2').html(Goods[i].header);
alpha.find('p').html(Goods[i].text);
alpha.find('div.notification').attr('id', Goods[i].notification);
$('#repeater').append(alpha);
}
}
karma and Goods are the name of the arrays in the JSON file.
What am I doing wrong?
Here is my JSON array for karma:
{
Goods : [{
"header": "Apple",
"text": "hi"
"picture": "appleImage",
"notification": "appleNote"
}, {
"header": "Pear",
"text": "hi",
"picture": "pearImage",
"notification": "pearNote"
}, {
"header":hi",
"picture": "bananaImage",
"notification": "bananaNote"
}, {
"header": "Dog",
"text": "hi",
"picture": "dogImage",
"notification": "dogNote"
}, {
"header": "Cat",
"text": "hi",
"picture": "catImage",
"notification": "catNote"
}, {
"header": "Snake",
"text": "hi",
"picture": "snakeImage",
"notification": "snakeNote"
}],
karma : [{
"karmaYinYangScore": "200",
"KarmaGiveScore": "40",
"KarmaTakeScore": "99",
"ItemsGiveScore": "20",
"ItemsTakeScore": "77"
}];
}
I can only guess what your data looks like, but since you said "karma and Goods are the name of the arrays", I'm going to assume we're talking about something like this:
{
karma: [{
karmaYinYangScore:'some value',
KarmaGiveScore:'some value',
KarmaTakeScore:'some value',
ItemsGiveScore:'some value',
ItemsTakeScore:'some value'
}
],
Goods: ['more','array','values']
}
If that's the case, we've got a few issues in your code.
First, getJSON returns one data result, so you should be referencing only that data returned.
function getJSON() {
$.getJSON('goods.js', function( data ) {
crazyFun( data.Goods ); // reference Goods array from data response
addScores( data.karma ); // reference karma array from data response
});
}
Then, your .addScores() function doesn't accept a parameter. You need some reference to receive the array being passed.
// Reference to the array being passed to the function
// ---------------v
function addScores( karma ) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
These are the only errors I see. Beyond that, the solution depends on the actual data structure of the response.
According to jQuery's documentation on the getJSON function (http://api.jquery.com/jQuery.getJSON/), your callback's parameters appear to be misleading. Your callback...
function(Goods, karma) {
crazyFun(Goods);
addScores(karma);
}
...appears to be expecting the arrays of data to be passed to it automatically, but jQuery actually passes the whole JSON result as the first parameter, and the status of your request as the second parameter, regardless of how the JSON is structured. Your callback should probably look more like this:
function(json, status) {
crazyFun(json.Goods);
addScores(json.karma);
}
This assumes that your JSON is well formed, and that the "Goods" and "karma" properties are properties of the root object. You may need to modify the callback if your JSON is structured differently.