将HTML表单转换为JSON对象

时间:2016-06-14 19:16:14

标签: javascript jquery html json xml

我想将HTML表单转换为JSON对象。表单基本上包含两个部分,Header和Detail。 Header部分包含一些HTML Input框,Detail部分是Table。我的表格的虚拟视图如下。

<!DOCTYPE html>
<html lang="en">
<body>
	<form id="MyForm" method="POST">
	<div name="HeaderData">
		<label id="lblFname">First Name:</label>
		<input type="text" name="fname"/> <br/>
		<label id="lblLname">Last Name:</label>
		<input type="text" name="lname" /> <br/>
		<label id="lblEmail">Email:</label>
		<input type="text" name="email" /> <br/>
	</div>
	<div id="DetailData">
		<table cellspacing="0" align="Center" rules="all" border="1" id="MyTable" style="width:940px;border-collapse:collapse;">
			</thead>		
					<th scope="col">Code</th>
					<th scope="col">Name</th>
					<th scope="col">Continent</th>
					<th scope="col">Region</th>
					<th scope="col">Population</th>
					<th scope="col">Independence Year</th>
			</thead>
			<tbody>
				<tr>
					<td name="Code">Ind</td>
					<td name="Country">India</td>
					<td name="Continent">Asia</td>
					<td name="Region">Asia</td>
					<td name="Population">113Core</td>
					<td name="Independence">1947</td>
				</tr>
				<tr>
					<td name="Code">Ind</td>
					<td name="Country">India</td>
					<td name="Continent">Asia</td>
					<td name="Region">Asia</td>
					<td name="Population">1500000</td>
					<td name="Independence">1947</td>
				</tr>
			</tbody>
		</table>
	</div>
</body>
</form>
</html>

我希望生成的JSON对象能够模仿:

{"HeaderData":[{"Fname":"XYZ","LName":"ABC","Email":"ABC@XYZ.COM"}],
 "DetailData":[{"Code":"Ind","Name":"India","Continent":"Asia","Region":"Asia","Population":"113 Crore","Independence Year":"1947"}],
 "DetailData":[{"Code":"Ind","Name":"India","Continent":"Asia","Region":"Asia","Population":"113 Crore","Independence Year":"1947"}]
}

我尝试过不同的库,比如jquery.tabletojson.js,但是他们无法将数组分配给单独的变量。

稍后我想将此JSON对象转换为XML String,以便我可以在SQL Server QUERY中处理它。我希望XML String能够模仿:

enter code here
<Root>
	<HeaderData>
		<FName>XYZ</FName>
		<LName>XYZ</LName>
		<Email>abc@xyz.com</Email>
	</HeaderData>
	<DetailData>
		<Code>Ind</Code>
		<Name>India</Name>
		<Continent>Asia</Continent>
		<Region>Asia</Region>
		<Population>113Crore</Population>
		<IndependenceYear>1947</IndependenceYear>
	</DetailData>
	<DetailData>
		<Code>Ind</Code>
		<Name>India</Name>
		<Continent>Asia</Continent>
        <Region>Asia</Region>
		<Population>113Crore</Population>
		<IndependenceYear>1947</IndependenceYear>
	</DetailData>
</Root>

我目前的优先事项是构建JSON STRING。一旦JSON可用,我就可以将数据转换为XML。

1 个答案:

答案 0 :(得分:0)

如果你所有<td>&#39;标签有一个名称属性,然后你可以用几行jQuery将它转换为一个JSON对象......

var poop = [];
$("#MyTable").find("tr").each(function(){
    var fart = {};
    if(!$(this).find("td").length) return;
    $(this).find("td").each(function(){
        fart[$(this).attr("name")]=$(this).text();
    });
    poop.push(fart);
});

console.log(poop);

以下是一个工作示例:fiddle.