I have a Javascript JSON object
const student = { name: "bob", age: 7, grade: 6 }
and I can pass it to my Web API using axios POST command by
JSON.stringify(student)
and I can build my student object by looping an array and passing in a value such as
let studentArr= []
const student = { name: studentArr[i]["name"], age: studentArr[i]["age"], grade: studentArr[i]["grade"}
I'm using i in the example as the index because it could have 100 students. As long as I pass in only one value for i, everything works fine. My question is how can I make it into a multi-element JSON object from my array. I've been spoiled by Newtonsoft.Json where I can pull data from a SQL database and create a JSON object. If I just JSON.stringify(studentARR) is shows empty. I want to pass to the Web API all of the students on one post so the Web API can make a document and download it back.
I seen many different ways of trying to accomplish this and the methods seem to change over time. Thanks for the help
Why do you have to JSON.stringify if you are using axios. The declaration of axios.post accepts URL as first parameter and the data which is formdata or the JSON object as second parameter
I'm pretty sure that you might not need to use JSON.stringify if you are using axios to post to a Web API
Example of using Axios post method https://axios-http.com/docs/post_example
I need to create a function that will use an object passed in the url. The goal is to update menu items for a restaurant. The query sent will look like this:
?restId=1&posId=1&groups=…&items= [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]&pizzas=[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]
When I run const queryObject = url.parse(req.url,true).query; it prints:
[Object: null prototype] {
restId: '1',
posId: '1',
groups: '…',
items: ' [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]',
pizzas: '[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]'
}
My problem is that I cannot access any of the values in items. I was given this url, so I cannot change it at all. How can I parse items in order to access the values?
The value of items and pizzas are both JSON formatted strings. You have to parse them to access the contained data. This is accomplished by calling JSON.parse()
So in your case, to access items, you could do the following:
const items = JSON.parse(queryObject.items)
The only problem you have now is that items isn't actually a valid JSON string. It's missing four closing tags }]}] at the end. I'm not sure if that's a transcription error or if you're actually getting a malformed URL, but that will cause you issues if the URL in your question is accurate.
For example, I have this Model as Users:
var Users = Spine.Model.sub();
Users.configure('Users', 'name', 'gender', 'age');
Users.extend(Spine.Model.Ajax);
Users.extend({url:"/users"});
Assume that we already have some data saved in database.
If run
var users = Users.fetch();
Ajax will send a GET request to /users, and all results will be returned.
But if I wanna fetch all female or male users, or age above 25, or top 10 users in specified order, how to pass these variables? I cant find spec in the document. The fetch method can pass a callback function parameter to revoke when fetch complete, clearly not what I want.
I found the solution myself..Actually the document tells how to paginate results.
var Photo = Spine.Model.sub();
Photo.configure('Photo', 'index');
Photo.extend(Spine.Model.Ajax);
Photo.extend({
fetch: function(params){
if ( !params && Photo.last() )
params = {data: {index: this.last().id}}
this.constructor.__super__.fetch.call(this, params);
}
});
But I found the code can't run, first
this.constructor.__super__.fetch.call(this, params);
should be
this.__super__.constructor.fetch.call(this, params);
secondly, if run Photo.fetch({data:{id:1}}), it will send a GET request like this
GET /photos?[object%20Object]
correct it
Photo.fetch({data: $.param({id:1})});
HTTP Request
GET /photos?id=1
I have a REST API serving a few URLs:
/rest/messages
provides all messages. A message is a JSON/Backbone Model
{
title: 'foo',
body : 'bar'
}
To get a single message I have:
/rest/messages/:id
Is it possible to fetch a Backbone Collection using message IDs array? I don't want the whole message list, but just a few messages I specify by ID.
I could fetch Models one-by-one and fill up the Collection, but I'm wondering if Backbone has a cleaner way to do this.
Thanks
According to documentation, you can pass ajax options to the fetch call. So, you can pass ids as data attribute to the fetch call being done and based on it, return the respective models from the server.
For example (when doing fetch),
collection.fetch({
data : {
message_ids : [1, 3, 5] // array of the message ids you want to retrieve as models
}
})
This message_id array will be accessible as parameters (not sure of the name in your case) in the server code being executed at /rest/messages, from there you can return only specific models based on ids you receive as message_ids. The only thing you need is, client side must be aware of the ids of all the message models it needs.
You can use any data structure instead of array to send message_ids.
The url property of collection reference to the collection location on the server. When you use fetch, backbone uses that url.
The url property can be also a function that returns the url. So you can do something like that:
var ids = [1,2,3]
var messages = new MessegecCollection();
messages.url = function() {
return "/rest/messages/"+ids.join("-"); //results "/rest/messages/1-2-3"
}
messages.fetch();
You can also create a method in your collection that generated and set the url, or even fetchs a set of models.
Now all you have to do is to support this url: /rest/messages/1-2-3
Hope this helps!
I have exposed to Backbone an API that returns user profiles with this structure:
{id: 1, following: {...}}. I only want to use the dictionary inside of the "following" attribute. How would I do that? Right now, I have a model with a URL to the API. I have a collection that uses this model. I do a fetch() on the collection, but I only want to use the dictionary inside of "following".
You should use parse to extract what you want from the the response:
parse model.parse(response)
parse is called whenever a model's data is returned by the server, in fetch, and save. The function is passed the raw response object, and should return the attributes hash to be set on the model.
So you'd want something like this in your model:
parse: function(response) {
return response.following;
}