1

I'm trying to serialize a javascript object but with a particular form(I think it has to be a method). Example:

var media = new Object();
media.url = "localhost";
media.foo = "asd"

var data=new Object();
data.title = "myTitle";
data.description = "myDescription";
data.media.push(media);

I need to serialize data this way:

"title=myTitle&description=myDescription&media[0].url=localhost&media[0].foo=asd"

The important thing is the way the array is written.

13
  • 2
    Is this being used with a jQuery AJAX function? If you give it an object as the data: option, it will serialize for you. Commented Jun 27, 2013 at 19:16
  • Tip: new Object == {} Commented Jun 27, 2013 at 19:16
  • 3
    You forgot to initialize data.media Commented Jun 27, 2013 at 19:17
  • 1
    Don't use new Object. Declare it using {}. var data = {title: "mytitle", media: [ {url: "localhost"} ]};. Commented Jun 27, 2013 at 19:19
  • 1
    @Federico: In that case, you don't need to serialize it, just do $.ajax({url: 'example.com', data: data});. Commented Jun 27, 2013 at 19:20

5 Answers 5

1

Check out Convert a JSON object's keys into dot notation paths and Convert complex JavaScript object to dot notation object. You can easily adapt those to handle your array keys special:

function transform(obj) {
    var result = {};
    recurse(obj, "");
    return result;
    function recurse(o, name) {
        if (Object(o) !== o)
            result[name] = o;
        else if (Array.isArray(o))
            for (var i=0; i<o.length; i++)
                recurse(o[i], name+"["+i+"]");
        else // if plain object?
            for (var p in o)
                recurse(o[p], name?name+"."+p:p);
    }
}

You can then apply $.param on the result to get the URL encoding etc:

$.param(transform(data))

(or just pass it into the data parameter of $.ajax).

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

Comments

0

There are multiple ways to serialize an object into a list (string) of parameters, have a look:

How to serialize an Object into a list of parameters?

One example is a method such as the below:

var str = "";
for (var key in obj) {
   if (str != "") {
       str += "&";
   }
   str += key + "=" + obj[key];
}

You can modify it to suit the style you need.

2 Comments

In addition to handling recursive objects, you need to call encodeURIComponent().
Thanks, I made something like your response
0

jQuery provides this via jQuery.param

var params = $.param(data);
console.log(params);

Produces:

title=myTitle&description=myDescription&media%5B0%5D%5Burl%5D=localhost&media%5B0%5D%5Bfoo%5D=asd

As you can see, it handles the nested array and object as you wish (%5B and %5D are URL encodings for [ and ]).

If you're using $.ajax() or one of its shortcuts, you don't need to call this explicitly. If you supply the object as the data argument or option, jQuery will automatically serialize it using this method.

Comments

0

you can use jQuery.param to do this:

$.param({a:'2', b: 1.2, c: "hello world"})// -> a=2&b=1.2&c=hello+world

EDIT

What I was missing above is the array support sorry bout that.

For this you'll need to decodeURIComponent()

var media = new Object();
media.url = "localhost";
media.foo = "asd"

var data=new Object();
data.title = "myTitle";
data.description = "myDescription";
data.media = [];
data.media.push(media);
alert(decodeURIComponent($.param(data)));

Output:

title=myTitle&description=myDescription&media[0][url]=localhost&media[0][foo]=asd

http://jsfiddle.net/bLu8Q/

Comments

0

Sorry, but I need to change. Thought it was easier but when looking at the result I saw that it was not so straight forward. If you're using jquery though you can simply do it like this:

var media = new Object();
media.url = "localhost";
media.foo = "asd"

var data=new Object();
data.title = "myTitle";
data.description = "myDescription";
data.media = []; // you forgot this...
data.media.push(media);

var data = $.param(data));

2 Comments

Wasn't asked for as far as I can see.
something like this, but with support for arrays

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.