Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Friday, February 12, 2010

django deep serializers

Django has it's own very nice serialization module. A very useful tool to serialize models in django projects. There is limitation to it, though.
When one serialize a model (table) which has relationship (ForeignKey) to other model, then you will only get the foreign_key, instead the whole object. Something like the following:

[ {
"pk": 1,
"model": "store.book",
"fields": {
"name": "Mostly Harmless",
"author": 42
}
} ]



In some cases, deep serializing is often necessary. Now, let me introduce you to this magnificent python module which extends django's built-in serializers. DjangoFullSerializers.
With this, you can get something like the following:

[ {
"pk": 1,
"model": "store.book",
"fields": {
"name": "Mostly Harmless",
"author": [ {
"pk": 42,
"model": "store.author",
"fields": {
"name": "John Doe",
"title": "Dr."
}
} ]
' }
} ]


I have used it and really satisfied with the result. Many thanks to the developer.

Tuesday, January 19, 2010

Serialize Form to JSON

I came across a handy javascript function to serialize form to JSON, taken from here

$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};


add above script to your document, then if you are using jQuery you can just do something like the following:

$("form#data").serializeObject();


and as per need, simply use json2.js to convert the (JSON) form object into string:
JSON.stringify($("form#invite_users").serializeObject());