DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

Recursive Rails Style Serialization For Javascript Objects

Snippets Manager user avatar by
Snippets Manager
·
Aug. 16, 06 · · Code Snippet
Like (0)
Save
Tweet
539 Views

Join the DZone community and get the full member experience.

Join For Free
Have you ever wanted to post from your javascript program to a Rails app so that the params are available to your application in a properly nested hash? Prototype makes this easy for form elements with it's Form Serializer, but it makes no provision for standard javascript objects.

Suffer no longer. With the following code you can serialize arbitrarily nested objects (eg, the sort of thing you get when you parse a JSON statement), so that it is ready to be posted via http to a Rails app.

The original Rails recursive Javascript object serializer.


var serializer = {
 
  serialize : function(object) {
    var values = []; 
    var prefix = '';
    
    values = this.recursive_serialize(object, values, prefix);
    
    param_string = values.join('&');
    return param_string;
  },
  
  recursive_serialize : function(object, values, prefix) {
    for (key in object) {
      if (typeof object[key] == 'object') {
        
        if (prefix.length > 0) {
          prefix += '['+key+']';         
        } else {
          prefix += key;
        }
        
        values = this.recursive_serialize(object[key], values, prefix);
        
        prefixes = prefix.split('[');
        
        if (prefixes.length > 1) {
          prefix = prefixes.slice(0,prefixes.length-1).join('[');
        } else {
          prefix = prefixes[0];
        }
        
      } else {
        value = encodeURIComponent(object[key]);
        if (prefix.length > 0) {
          prefixed_key = prefix+'['+key+']'          
        } else {
          prefixed_key = key
        }
        prefixed_key = encodeURIComponent(prefixed_key);
        if (value) values.push(prefixed_key + '=' + value);
      }
    }
    return values;
  }
}


Usage:


payload = new Object;
payload.comment = new Object;
payload.comment.title = "The Title";
payload.comment.body = "The body of the post.";
post_string = serializer.serialize(payload);


Result:


comment%5Btitle%5D=The%20Title&comment%5Bbody%5D=The%20body%20of%20the%20post.


Which gives you this in Rails:


params[:comment] #=>
{:title => "The Title", :body => "The body of the post."}
Serialization JavaScript Object (computer science)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top Six Kubernetes Best Practices for Fleet Management
  • Kafka Fail-Over Using Quarkus Reactive Messaging
  • Top Soft Skills to Identify a Great Software Engineer
  • How to Determine if Microservices Architecture Is Right for Your Business?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo