4

How can I serialize an object without using the $.param jquery?

I want the object below:

var user = {username: 'ronald.araujo', password: '123456',};

to have the following output:

username=ronald.araujo&password=123456

Any suggestions? Remembering that I would do this using Angularjs or pure Javascript.

EDIT:

I am using the verb "save" ($resource) the angularjs. How could I set the header "application / x-www-form-urlencoded" and serialize?

mikhail
  • 5,019
  • 2
  • 34
  • 47
Ronald Araújo
  • 1,395
  • 4
  • 19
  • 30
  • Do you mean serialize it to `application/x-www-form-urlencoded` format? There's a simple lib available here - https://github.com/iambumblehead/form-urlencoded – Phil Apr 01 '15 at 02:50
  • possible duplicate of [How do I POST urlencoded form data with $http in AngularJS?](http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs) – Phil Apr 01 '15 at 02:52
  • There's no built-in tool to do that in Angular afaik. But why do you want to do that? You can send any kinf of `GET` request without having to manually add the datat into the URL. – floribon Apr 01 '15 at 02:55

3 Answers3

6

Pure javascript can do it just fine:

function serializeObj(obj) {
    var result = [];

    for (var property in obj)
        result.push(encodeURIComponent(property) + "=" + encodeURIComponent(obj[property]));

    return result.join("&");
}

var user = {
    username: 'ronald.araujo',
    password: '123456'
};

var serialized = serializeObj(user);
console.log(serialized); //username=ronald.araujo&password=123456

The link to original answer: How do I POST urlencoded form data with $http in AngularJS?

Community
  • 1
  • 1
Huy Hoang Pham
  • 4,107
  • 1
  • 16
  • 28
1

You can use $httpParamSerializerJQLike;

.controller(function($http, $httpParamSerializerJQLike) {
  //...

 var serializedUser = $httpParamSerializerJQLike(user);

});

you can see $httpParamSerializerJQLike Documentation here.

Mehul Mali
  • 3,084
  • 4
  • 14
  • 28
0

For angular 2 I think you can best use the following decorator https://github.com/pleerock/class-transformer to transform, serialize and deserialize objects.

To learn more about decorators see https://angular.io/docs/ts/latest/cookbook/ts-to-js.html

0x1ad2
  • 8,014
  • 9
  • 35
  • 48