如何将我的 json 数据加载到 html 表中,并使用纯 Javascript 将行作为单选按钮



我有一个json响应:

var jsondata = dojo.fromJson(response);

我有一个字符串

var jsonString = jsondata.items;

jsonString 是 JSON 文件

jsonString="[
                {macAddress:'aa:bb:Cc',domainName:'NMS',Priority:'first'},
                {macAddress:'ea:fb:Ca',domainName:'Network',Priority:'third'}, 
                {macAddress:'ca:bb:Ca',domainName:'Mesh',Priority:'second'}
            ]";

现在我想访问jsonString[0] {macAddress:'aa:bb:Cc',domainName:'NMS',Priority:'first'}的第一个对象。这是行不通的。这将显示"[",这是第一个元素,而不是第一个对象。

我也试过

jsondata.items[0];
jsondata[Object.keys(jsondata)[0]];
jsondata[1];

一切都说"未定义"。

有人可以帮忙吗?我需要提取这些数据并将其放在一个带有行作为单选按钮的表中

我认为您的json字符串中有错误,请尝试使用 jsonlint.com 验证json

请在下面找到工作代码:

$(document).ready(function(){
    var jsonString = '[{"macAddress": "aa:bb:Cc","domainName": "NMS","Priority": "first"},{"macAddress": "ea:fb:Ca","domainName": "Network","Priority": "third"},{"macAddress": "ca:bb:Ca","domainName": "Mesh","Priority": "second"}]';	
    var row = '';    	
	
    $.each($.parseJSON(jsonString), function(index, value){
        row += '<tr><td>&nbsp;</td><td><input type="radio" name="test" /> '+ value.macAddress +'</td></tr>';
		});
    $('#tbl tbody').html(row);
});
 <!doctype html>
<html>
<head>
	<title>Stackoverflow</title>
</head>
<body>
	<div class="container">
		<table id="tbl">
			<thead>
				<tr>
					<th>&nbsp;</th>
					<th>Description</th>
				</tr>
			</thead>
			<tbody>
			</tbody>
		</table>
	</div>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</body>
</html>

var jsonString = '[{"macAddress": "aa:bb:Cc","domainName": "NMS","Priority": "first"},{"macAddress": "ea:fb:Ca","domainName": "Network","Priority": "third"},{"macAddress": "ca:bb:Ca","domainName": "Mesh","Priority": "second"}]';
var jsonObject = JSON.parse(jsonString);
//build head
var head = '<tr>';
for(key in jsonObject[0]){
    head +='<th>&nbsp;</th><th>'+key+'</th>';
}
head +='</tr>';
//build rows
var rows = jsonObject.map(function(element){
            var row = '<tr>';
            for( key in element){
                row += '<td>&nbsp;</td><td><input type="radio" name="'+key+'" /> '+ element[key] +'</td>';  		
            }
            row += '</tr>';
            return row;
         });
//adding to table
var tbl_head = document.getElementById('tbl').getElementsByTagName('thead')[0];
var tbl_body = document.getElementById('tbl').getElementsByTagName('tbody')[0];
tbl_head.innerHTML = head;
tbl_body.innerHTML = rows.join('');
<!doctype html>
<html>
	<head>
		<title>Stackoverflow</title>
	</head>
	<body>
		<div class="container">
			<table id="tbl">
				<thead></thead>
				<tbody></tbody>
			</table>
		</div>    		    		
	</body>
</html>

最新更新