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?

3
  • Do you mean serialize it to application/x-www-form-urlencoded format? There's a simple lib available here - github.com/iambumblehead/form-urlencoded Commented Apr 1, 2015 at 2:50
  • possible duplicate of How do I POST urlencoded form data with $http in AngularJS? Commented Apr 1, 2015 at 2: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. Commented Apr 1, 2015 at 2:55

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

1

You can use $httpParamSerializerJQLike;

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

 var serializedUser = $httpParamSerializerJQLike(user);

});

you can see $httpParamSerializerJQLike Documentation here.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.