How to use Array attributes in sails.js model - javascript

Hi i am a new bee to sails and trying to get a model api that finally gives output as follows
[
{
"icon" : [
{"name":"ico1", "ico_typ":"fb", "ico_content_URL":"someLocation"},
{"name":"ico2", "ico_typ":"tw", "ico_content_URL":"someLocation"},
{...}
]
"createdAt":
"updatedAt":
}
]
I thought i can achieve this by passing the icon attribute as an Array but the problem is it passes the whole Array as string when i load it in REST CLIENT also i could not use the validation for values inside Array like without ico_type and URL the data should not be loaded into database. So, any suggestion about use of the 'array' where i'm wrong is very appreciated, thanks so much!
Sails_v0.11.0
MongoDB_3.0.1

In your model define a method
toJSON: function () {
var obj = this.toObject();
//say your obj.icon returns something like `'[{"name":"ico1","ico_typ":"fb","ico_content_URL":"someLocation"},{"name":"ico2","ico_typ":"tw","ico_content_URL":"someLocation"}]'`
obj.icon = JSON.parse(obj.icon)
return obj;
},

I think the model WaterLine gave you is already an JSON format, all you need to do is to use the right way to response it.
res.json(model);

Related

Issue with i18n parsing

I am getting JSON fro backend, which I need to parse on UI.
For all the keys from the JSON, I have to translate them and show on UI.
Eg:
i18n.t('key') will give me translated value.
But for some keys like 'name', 'date'
Eg:
i18n.t('name')
translation is giving following output
"key 'translation:name (en-US)' returned a object instead of string."
Could you please help me how to deal with this scenerio.
If you have for example following JSON from your service
{
"i18n": {
"name": "translation1",
"name2": "translation2"
}
}
You can just use it as following
var mytranslation = getTranslationsFromService();
console.log(mytranslation.i18n.name) //result: translation1
console.log(mytranslation.i18n.name2) //result: translation2
var getTranslationsFromService = function() {
//Get result from service, where the result looks like the JSON above.
}
I hope I could help.
Kind regards.

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Passing an array of ints with node-soap

I'm using node-soap with a service and everything works but I need to send an array of ints and I find that I can only send the first one because I can't find the correct way to build a JS object to represent this array.
I've been looking at similar questions but I couldn't find the answer to my question.
I need to generate a XML property like the following one:
<ns1:ArrayOfInts>
<!--Zero or more repetitions:-->
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:ArrayOfInts>
by passing an object that contains the array:
soapObject = {
somefields,
"ns1:ArrayOfInts": {
Something goes here
},
};
Any idea how to create the JS object?
I had the same problem and used $xml property to add raw XML to the request and attributes to set the arr namespace:
var fields = [2904, 3089, 4531];
soapObject.arrayOfInts = {
attributes: {
'xmlns:arr': 'http://schemas.microsoft.com/2003/10/Serialization/Arrays'
},
$xml: fields.map(function(value) {
return '<arr:int>' + value + '</arr:int>';
}).join('')
};
This code will generate the following request:
<ns1:arrayOfInts xmlns:arr="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<arr:int>2904</arr:int>
<arr:int>3089</arr:int>
<arr:int>4531</arr:int>
</ns1:arrayOfInts>

Json stringify then parse from URL

I seem to be having an issue in stringify'ing then pasing from a url object
I simply stringify my object and set the location (with angulars $location) like so
currentUrl = {"module1" : {"is" : true} }
$location.search(JSON.stringify(currentUrl));
So this parses to the url just fine, however when I try to grab it from the url i get this back
console.log($location.search());
---
Object {{"module1":{"is":true}}: true}
How do I parse this back into an object so I can use it? If I do
JSON.parse($location.search());
I get a syntax error. I maybe because of how search returns the object? I am a bit confused here, could use some help. Thanks!
So I put it in the url with
$location.search(JSON.stringify(currentUrl));
What are the steps I need to take to get it back into this form :
{"module1" : {"is" : true} }
Edit -
It just appears it's setting the json object as the key in the location like
{ "mystrigifiedobject": true }
Edit2 :
based off the first edit, I was able to solve it (assming it's set in the locations object key) like so :
currentUrl = $location.search();
currentUrl = JSON.parse(Object.keys(currentUrl));
console.log(currentUrl);
This just feels a little weird though, am I doing something wrong here?
$location.search() returns the parsed search items from the url path as an object. This means this kind of url:
?a=b&c=d
will result in this object:
{ a: 'b', c: 'd' }
When you call this function:
currentUrl = {"module1" : {"is" : true} }
$location.search(JSON.stringify(currentUrl));
your path will look like this:
?%7B%22module1%22:%7B%22is%22:true%7D%7D
and the parsed object returned from $location.search will look like this:
{{"module1":{"is":true}}: true}
not that this is an object with one entry and the key is your JSON
So what you need to do in order to get your object back is this:
var parsedObject = $location.search();
var yourObject = JSON.parse(Object.keys(parsedObject)[0]);
see this jsfiddle: http://jsfiddle.net/HB7LU/11633/
But please note: you should encode your string when putting it in a url:
$location.search(encodeURIComponent(JSON.stringify(currentUrl)));
$routeParams provides access to both routing template values and query string values (as a string).
function ctrl($routeParams) {
var yourValueAsString = $routeParams.yourKey;
}
function ctrl2($location) {
$location.search('yourKey', JSON.stringify(...));
}
A better alternative would be to switch to using the UI Router which deals with this better.

How to pass a List to javascript in JSF

I am struggling with a JSF project.
In my service, I retrieve a List of custom object (here Sales), and I have to pass it to my jsf view, specifically into the javascript, to make graphs.
My problem is, I don't understand how to send the data from the controller (my managed beans) to my view, and which tag to use in my view to retrieve it in my javascript.
I think I can pass my data like this, but I'm not sure
public String passData() {
List<Sales> bestSelling = saleService.getBestSellingProduct(null, null, null, null);
List<Sales> worstSelling = saleService.getWorstSellingProduct(null, null, null, null);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("bestSelling", bestSelling);
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("worstSelling", worstSelling);
return "./all.jsf?faces-redirect=true";
}
You need to create a JSON object that you'll assign to a JavaScript variable. To create JSON you may find useful to incorporate a library like Gson.
So, it'll look like:
var sales = #{bean.jsonList};
with Bean#getJsonList as:
public String getJsonList() {
return (sales == null) ? "" : new Gson.toJson(sales);
}
Just don't forget that the script with such assignment must be handled by the FacesServlet.

Categories

Resources