Progger
Progger

Reputation: 2254

How to properly compile html form data into JSON object

I have a form which collects some information (asset cost, asset description, shareholders, and how much each of the shareholders own). I want to compile all this information in a JSON object and post it. When I collect the data and JSON.stringify() it, it looks like this:

[ { name: '1', value: '50' },
{ name: 'asset_desc', value: 'boat' },
{ name: 'asset_cost', value: '100' },
{ name: 'org_id', value: '2' },
{ name: '3', value: '50' },
{ name: 'asset_desc', value: 'boat' },
{ name: 'asset_cost', value: '100' },
{ name: 'org_id', value: '2' } ]

I want to clean this data up before posting so it looks like this:

{
    "asset_desc": "boat",
    "asset_cost": "100",
    "org_id": 2,
    "share_holders": {
        "1": "50",
        "2": "50"
    }
}

I am running jQuery. Does jQuery have some built-in helpers that would make the cleaning up of this data simple? The function I'm using to get the data like this in the first place is:

formdata = $('#addpurchaseform');
data = JSON.stringify(formdata.serializeArray());

Is there a better way to do this so that my data is in a cleaner state? Am I even thinking about this correctly (I am new to web development)?

Not sure if this matters, but the receiving end of this is Python / Django so I figured it would be better if I sent a clean JSON object rather than trying to parse / clean the mess after it was received.

Upvotes: 0

Views: 110

Answers (1)

TwilightSun
TwilightSun

Reputation: 2335

If you're looking for a jQuery plugin, then try this: https://github.com/marioizquierdo/jquery.serializeJSON

Upvotes: 1

Related Questions