23

Say I have something like:

var obj = {id: 1, name: "Some name", color: "#444444" };

I want to serialize that object. I tried:

$(obj).serialize();

but that didn't work.

Any ideas?

rjmunro
  • 27,203
  • 20
  • 110
  • 132
Seamus James
  • 981
  • 3
  • 12
  • 25

3 Answers3

41

You should use jQuery.param() instead.

Working Example

With vanilla JS, you would use JSON.stringify instead.

Community
  • 1
  • 1
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Just a small correction: method name should be "stringify" (with small s) because JavaScript is case sensitive. – Gábor Nagy Oct 03 '13 at 08:43
7

As mentioned you should use .param()

$.param({id: 1, name: "Some name", color: '#444444' })

But also you need to be careful with your syntax. Your brackets don't match, and that color will need quotation marks. jsFiddle

Sinetheta
  • 9,189
  • 5
  • 31
  • 52
4

You could use JSON.stringify to serialize your object, and you'd have to wrap your color string correctly:

var obj = {id: 1, name: "Some name", color: '#444444' };
var serialized = JSON.stringify(obj);
// => "{"id":1,"name":"Some name","color":"#444444"}"
Tharabas
  • 3,402
  • 1
  • 30
  • 29