what is the best way to save observable objects to JSON without _backingData etc.?
For example instead of:
[{"_backingData":{"name":"Test","hourlyRate":""},"name":"Test","hourlyRate":"","id":-1,"number":"","backingData":{"name":"Test","hourlyRate":""}}]
This should be saved:
[{"name":"Test","hourlyRate":"","id":-1,"number":""}]
This is my code to save the data:
var data = JSON.stringify(value.concat());
Windows.Storage.ApplicationData.current.localFolder.createFileAsync("customer.json", Windows.Storage.CreationCollisionOption.replaceExisting)
.then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file, data);
});
value is a WinJS.Binding.List().
Is there a simple solution to solve this "problem"?
use WinJS.Binding.unwrap over the individual elements in the array.
Related
I'm new to ionic 3. i need to store a array element in local storage.
I tried this code but it only storing the array. Not an array element
This is my code:
signin() {
this.showLoader();
console.log(this.loginData);
this.authService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.data = result;
console.log('Result:'+JSON.stringify(result));
localStorage.setItem('token', JSON.parse(JSON.stringify(this.data))._body.access_token);
console.log(JSON.parse(JSON.stringify(this.data))._body.access_token);
this.navCtrl.setRoot(DashboardPage);
and this is an result value
Result:{"_body":"{\"access_token\":\"J0ErN5qf4btTJaB27FLMNLTrhwBxZMTCBAxc4m25\",\"token_type\":\"Bearer\",\"expires_in\":3600,\"refresh_token\":\"OMVvOXHgsfKwWtHyYwjlzsO5Jxb44H0Oi9lf7Pk6\"}",
In short, i need to store the access_token in local storage. please suggest some method.
Thanks in advance
The problem is how are you storing the value in the localStorage, the correct implementation would be:
Save to localStorage:
localStorage.setItem('token', JSON.stringify(this.data._body.access_token));
Get from localStorage:
JSON.parse(localStorage.getItem('token'));
I would like to reach a specific property of the data that I have returned from my service.
So basically I want to be able to somehow reach $scope.users.name, I know that the users are the objects in the array, but could I reach that specific property in any way? Hopefully the question is clear enough?
$scope.users = [];
UserService.getAll().then(
function (data) {
$scope.users = data;
}, function (err) {
console.log(err);
}
);
I am assuming the data you receive is in the form of an array. If you know the index then you can do
$scope.users[2].name
Where 2 is the index of the object you want to know the name property of.
Or you can try a js function forEach
$scope.users.forEach(function (user) {
console.log(user.name);
});
The function will iterate over all the objects and you can access their properties inside the callback which is passed in.
Hope that is what you're looking for.
I have a standard JSON response in an Angular controller, which returns data.
I am trying to get specific parts of that data, and manipulate it and use the manipulated version within the code.
Currently i have:
$http.get('/json/file.json').success(function(data) {
$scope.results = data;
});
In the JSON, i have data such as this:
"hotels":[
{
"region": "Indian Ocean"
}
]
In my code, i am using ng-repeat to call "hotel in results.hotels" and using "hotel.region".
How do i grab the hotel.region from the data, and remove the space between the words, replace the space with a '_' and make it all lower case so i end up with "indian_ocean". As well as this, how would i then use this within my ng-repeat?
Many thanks..
data.hotels[0].region.replace(" ","_").toLowercase()
Just do...
$scope.results.forEach(function (element) {element.replace(" ","_").toLowercase()});
I figured it out so this can be used in a more general way.
Create a new filter...
app.filter('removeSpaces', function () {
return function (text) {
var str = text.replace(/\s+/g, '_');
return str.toLowerCase();
};
});
Then this can be used site-wide by calling "{{hotel.region | removeSpaces}}".
Thanks to the people who did respond and for their help.
I've tried getting information with JSON only with one function, and it works fine. When it becomes two or more though it was pointed out that an array of array should be used.
How can you decode this information?
get.php
$response = array("home"=>$home, "topr"=>$top);
echo json_encode($response);
test.js
$(document).ready(function() {
$.get("php/get_ratings.php")
.done(function(data) {
var results = jQuery.parseJSON(data); // Should I change this?
$.each(results, function(i, value) { // Or this?
})
});
});
What PHP calls "arrays" are not what most languages call "arrays," including both JSON and JavaScript. Your response will be in this form:
{"home": something, "topr": something}
In your code:
No, you don't need to parse it, jQuery will do that for you if it's being sent correctly (e.g., with Content-Type: application/json).
You can access .homeand .topr properties on the object you receive.
E.g.:
$( document ).ready(function() {
$.get( "php/get_ratings.php")
.done(function(data) {
// use data.home and data.topr here
});
});
What you do with them depends on what they are, which you haven't shown. If they're numerically-index arrays (what most languages call arrays), your response will look like this:
{"home":["stuff","here"], "topr": ["stuff","here"]}
...and .home and .topr will be JavaScript arrays.
If they're PHP associative arrays like your top level thing, then they'll come through as objects, with properties named after the keys of the associative array.
I would like to know if any better way to create multiple collections fetching from a single big JSON file. I got a JSON file looks like this.
{
"Languages": [...],
"ProductTypes": [...],
"Menus": [...],
"Submenus": [...],
"SampleOne": [...],
"SampleTwo": [...],
"SampleMore": [...]
}
I am using the url/fetch to create each collection for each node of the JSON above.
var source = 'data/sample.json';
Languages.url = source;
Languages.fetch();
ProductTypes.url = source;
ProductTypes.fetch();
Menus.url = source;
Menus.fetch();
Submenus.url = source;
Submenus.fetch();
SampleOne.url = source;
SampleOne.fetch();
SampleTwo.url = source;
SampleTwo.fetch();
SampleMore.url = source;
SampleMore.fetch();
Any better solution for this?
Backbone is great for when your application fits the mold it provides. But don't be afraid to go around it when it makes sense for your application. It's a very small library. Making repetitive and duplicate GET requests just to fit backbone's mold is probably prohibitively inefficient. Check out jQuery.getJSON or your favorite basic AJAX library, paired with some basic metaprogramming as following:
//Put your real collection constructors here. Just examples.
var collections = {
Languages: Backbone.Collection.extend(),
ProductTypes: Backbone.Collection.extend(),
Menus: Backbone.Collection.extend()
};
function fetch() {
$.getJSON("/url/to/your/big.json", {
success: function (response) {
for (var name in collections) {
//Grab the list of raw json objects by name out of the response
//pass it to your collection's constructor
//and store a reference to your now-populated collection instance
//in your collection lookup object
collections[name] = new collections[name](response[name]);
}
}
});
}
fetch();
Once you've called fetch() and the asyn callback has completed, you can do things like collections.Menus.at(0) to get at the loaded model instances.
Your current approach, in addition to being pretty long, risks retrieving the large file multiple times (browser caching won't always work here, especially if the first request hasn't completed by the time you make the next one).
I think the easiest option here is to go with straight jQuery, rather than Backbone, then use .reset() on your collections:
$.get('data/sample.json', function(data) {
Languages.reset(data['Languages']);
ProductTypes.reset(data['ProductTypes']);
// etc
});
If you wanted to cut down on the redundant code, you can put your collections into a namespace like app and then do something like this (though it might be a bit too clever to be legible):
app.Languages = new LanguageCollection();
// etc
$.get('data/sample.json', function(data) {
_(['Languages', 'ProductTypes', ... ]).each(function(collection) {
app[collection].reset(data[collection]);
})
});
I think you can solve your need and still stay into the Backbone paradigm, I think an elegant solution that fits to me is create a Model that fetch the big JSON and uses it to fetch all the Collections in its change event:
var App = Backbone.Model.extend({
url: "http://myserver.com/data/sample.json",
initialize: function( opts ){
this.languages = new Languages();
this.productTypes = new ProductTypes();
// ...
this.on( "change", this.fetchCollections, this );
},
fetchCollections: function(){
this.languages.reset( this.get( "Languages" ) );
this.productTypes.reset( this.get( "ProductTypes" ) );
// ...
}
});
var myApp = new App();
myApp.fetch();
You have access to all your collections through:
myApp.languages
myApp.productTypes
...
You can easily do this with a parse method. Set up a model and create an attribute for each collection. There's nothing saying your model attribute has to be a single piece of data and can't be a collection.
When you run your fetch it will return back the entire response to a parse method that you can override by creating a parse function in your model. Something like:
parse: function(response) {
var myResponse = {};
_.each(response.data, function(value, key) {
myResponse[key] = new Backbone.Collection(value);
}
return myResponse;
}
You could also create new collections at a global level or into some other namespace if you'd rather not have them contained in a model, but that's up to you.
To get them from the model later you'd just have to do something like:
model.get('Languages');
backbone-relational provides a solution within backbone (without using jQuery.getJSON) which might make sense if you're already using it. Short answer at https://stackoverflow.com/a/11095675/70987 which I'd be happy to elaborate on if needed.