My json file looks like this:
[
{
"id" : "1",
"type" : "hardware"
},
{
"id" : "2",
"type" : "software"
}
]
Now when I run following code :
$http({
method: 'get',
url: '/tools.json'
}).success(function(data, status, headers, config) {
///whatever
})
I get these two objects for rederning via ng-repeat, that's fine.
Now, I want to create filters in my app, like display only "Hardware" or "Software", for this, which is the best way to achieve this, is there a way where I can just get Hardware typed objects from JSON itself? (querying JSON and get matching objects) and how can I do that? What should I change in code in-order to do this or should I use Angular filters to render Hardware types after getting entire JSON.
I don't have much experience in Angular, let me know if there is any other way I can achieve what I want.
Thanks in advance.
It's your choice completely.
Ideally, your backend should be returning the JSON filtered by the query.
If you want instant-responsiveness, you may use Angularjs's filters to do the filtering for you on the same data which you'd fetch once from the server. This also has an added benefit of doing full-text search, which is really neat.
If you just want to filter the JSON data, you could use the reduce method as follows:
var hardware = data.reduce(function(result, current) {
if(current.type === 'hardware') {
result.push(current);
}
return result;
}, []);
Fiddle available here.
The ideal place for this filtering would be on backend, given the type. But for some reason, if you want to do this on browser, you can use a simple for loop to filter objects with type hardware. A cleaner way of doing this would be with underscore. Include underscore source file in your project and do _.filter function to filter the objects you want. You can read more about filter function here: http://underscorejs.org/#filter
Related
I'm sending a JS object from my front-end to my Java backend, and I'm passing a object like so, which contains different types
wrapperObject = {
JSONOBJ = {
'key': 'value'
},
id: '123',
date: 'exampledate'
}
My java backend then takes this wrapperObject and converts every field inside into a value inside of a hashmap Map. Whenever it reaches the JSONObject, however, it parses it and attempts to insert into the db and I reach a
bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: No hstore extension installed.
What can I do about this, and is there a better way of approaching this?
It sounds like it may be as simple as adding the hstore extension. The PostgreSQL documentation for installation looks pretty straightforward:
Let me know if I'm missing something, hope this helps!
I'm having a little trouble wrapping my mind around a problem and could use a little help.
I'm developing an app in Rails using Angular.js for my client-side MVC framework and have created a service by which Angular can get images. It's pretty straightforward:
var ImageServices = angular.module("ImageServices", ["ngResource"]);
ImageServices.factory("Image", ["$resource",
function ($resource) {
return $resource("/images/:id.json", {}, {
"query" : { method: "GET", params: {}, isArray: true },
"update" : { method: "PUT", params: { id: "#id" } },
"remove" : { method: "DELETE" }
});
}
]);
The above service is probably a bit too generic for my purposes. What I'd like for the service to provide me is all images associated with a given user. I suppose I could accomplish this by nesting the desired image data within the user's data, like this:
user = {
// user attributes
blah: "blah",
//image objects
images: [
{}
]
}
Or maybe I could somehow write code in Rails that will return all images associated with the user, thus:
http://localhost:3000/users/1/images.json
Or maybe I could just make a service for each type of data that I'd like returned to Angular.
Architecturally, I'm not sure what makes sense. Could someone provide some insight into what the best possible path might be? If there are no hard and fast answers, I'm not opposed to reading a book on the topic if you could recommend one. Thanks!
The $resource service is kind of like a wrapper for the $http service. It has methods built into it.
services.factory('Images', ['$resource',
function($resource) {
return $resource('/images/:id', {id: '#id'});
}]);
The #id tells it to pick the id field from its object and use that as the id parameter.
So in your case, you could do {id: '#user'}.
The above resource give you access to:
Images.get() //GET Single JSON
Images.save() //POST Single JSON
Images.query() //GET JSON Array
Images.remove() //DELETE Single JSON
Images.delete() //DELETE Single JSON
Images.get({id: 15}) //will make return all images for a user through a call to /images/15.
I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.
I have the following code -
var options = new Ext.data.JsonStore({
model: 'options_model',
data: [
{ id: 1, option1: 'Alope', status1: 'true',option2: 'Option2', status2: 'false',option3: 'Option3', status: 'false',option4: 'Option4', status4: 'false' }
]
});
Now how can I retrieve data of option ???
I suggest you put your data into maybe a filename.json file (this is to maintain the scalability and integrity of your code).
Anyway, wherever it is you store your data, this is the code you need:
Ext.Ajax.request({
url: 'path_to_ur_json_file_wrt_html_file/filename.json', //in my case it was data/xyz.json since my folder layout was : abc.html, app, data, lib, stylesheets; and my data.json was in the data folder :)
timeout:3000, //how long it shud try to retrieve data in ms
method:'GET',
success: function(xhr) {
jsonData = Ext.util.JSON.decode(xhr.responseText);
var data4u = jsonData.data[0].option1;
}
});
First, JsonStore is not really a class to use. It's internal to Sencha and may be removed at any time. You should use Ext.data.Store instead.
Second, many of the out-of-the-box components in Sencha receive a store as confguration options so you don't have to worry about the inner workings.
Finally, if you do need to access store's data, you can do so by using each, getAt or find methods, depending on your needs and the way you want to access your data (random access, sequential or search).
I suggest you to go over this documentation:Sencha 1.1 Documentation
I've asked over on the Sencha Touch forums but haven't had a great response (well, none in fact). I wonder if anyone can help. I want to create a List of items from a JSON response received from a PHP script. Here's an example of the JSON received back from the PHP:
{
"friends":[
{
"friend":{
"id":"4",
"forename":"Chris",
"surname":"Major",
"verboseName":"Chris Major",
"phoneNumber":"07931655247",
"longitude":"-0.410909",
"latitude":"52.999245",
"email":"major#lincsmps.co.uk",
"lastRefresh":null,
"joinDate":"1294839423"
},
"networks":null,
"approved":"1"
},
{
"friend":{
"id":"2",
"forename":"Marta",
"surname":"Urbanowicz",
"verboseName":"Marta Urbanowicz",
"phoneNumber":"07716021468",
"longitude":"-0.0338518",
"latitude":"52.9773876",
"email":"urb.marta#googlemail.com",
"lastRefresh":null,
"joinDate":"1294836801"
},
"networks":null,
"approved":"1"
}
]
}
I would like to know how I can parse this into a DataStore and then output a grouped List in Sencha Touch. Although there are examples of using standard JSON responses for a ListView, there doesn't seem to be a nested example such as this...
Any help gratefully received.
Ben,
What you may want to do is declare your store of Friends with the fields with the fields you desire (maybe id, surname, email, network, approved)
Then when make a remote call with the Ajax remote call, which will just pass back the raw data.
At that point you'll have the "friends" object. You can then loop through each "friend" and instead of adding the "friend" in total create new objects:
var friend = {id:'2', surname:'whatever', email:'whatever#blah.com'}
Make an array of those new friend structures, and pass those into the store. This will flatten out or simplify your complex json structure.
Hope that helps, and I can provide more details if you need them.