简体   繁体   English

如何将html表单数据正确编译为JSON对象

[英]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. 我想在JSON对象中编译所有这些信息并将其发布。 When I collect the data and JSON.stringify() it, it looks like this: 当我收集数据和JSON.stringify()时,它看起来像这样:

[ { 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. 我正在运行jQuery。 Does jQuery have some built-in helpers that would make the cleaning up of this data simple? jQuery是否具有一些内置帮助程序,这些帮助程序可以使清除这些数据变得简单? 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)? 我什至在正确考虑这个问题(我是Web开发的新手)?

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. 不知道这是否重要,但是它的接收端是Python / Django,所以我认为如果发送干净的JSON对象而不是尝试在接收到混乱之后解析/清理,那会更好。

如果您正在寻找jQuery插件,请尝试以下操作: https : //github.com/marioizquierdo/jquery.serializeJSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM