我正在尝试读取以下 JSON 并将结果输出到 HTML 表中。 我只想将所有 EnvID 都放到 HTML 表中。我已经尝试过了,但它似乎不起作用。
代码:
function myFunction(response) {
var arr = JSON.parse(response);
var stringified = JSON.stringify(arr);
stringified.replace(/"\"/gm, '')
var jsonObject = JSON.parse(stringified);
var Profile = jsonObject.value[0].PROFILE;
var jsonProfile = JSON.parse(Profile);
alert(Profile); //This alert works, and outputs the whole JSON as expected.
var tbl=$("<table/>").attr("id","mytable");
$("#id01").append(tbl);
for(var i=0;i<jsonProfile.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["EnvId"]+"</td></tr>";
$("#mytable").append(tr+td1);
}
document.getElementById("id01").innerHTML = out;
}
HTML:
<!doctype html>
<style type="text/css">
#mainPopup {
padding: 10px;
height: 200px;
width: 400px;
font-family: Helvetica, Ubuntu, Arial, sans-serif;
}
h1 {
font-size: 2em;
}
</style>
<script src=popup.js></script>
<div id="mainPopup">
<h1>Hello extensionizr!</h1>
</div>
<div id="id01"></div>
JSON:
{
"Dashboard":1,
"Theme":0,
"Groups":[ somedata ],
"UserInfo":{ somedata },
"Shortcuts":[
{
"Dashboard":1,
"Index":0,
"EnvId":"1194"
},
{
"Dashboard":1,
"Index":1,
"EnvId":"2715"
},
{
"Dashboard":1,
"Index":2,
"EnvId":"2714"
},
{
"Dashboard":1,
"Index":3,
"EnvId":"2756"
}
]
}
我也有点困惑为什么这个 JSON 有不同的格式,比如 "Groups":[ somedata ]
有方括号 []
,而 "UserInfo":{ },
有大括号 {}
最佳答案
我找到了一个修复。
首先,我注意到在开始使用 javascript 时,您解析 JSON 响应,对其进行重新字符串化,然后对其进行篡改。我认为你不应该那样做。
只使用JSON解析的结果对象。您可以通过遍历 Shortcuts 数组来获取所有的 EnvId。这是一些代码。
function myFunction(response) {
//here you were parsing, restringifying and tampering with the JSON. I removed the later parts.
var obj = JSON.parse(response);
var tbl = $("<table/>").attr("id", "mytable");
$("#id01").append(tbl);
//Here I travel through the "Shortcuts" table, to display all the EnvIds as you wanted.
for (var i = 0; i < obj["Shortcuts"].length; i++) {
var tr = "<tr>";
var td1 = "<td>" + obj["Shortcuts"][i]["EnvId"] + "</td></tr>";
$("#mytable").append(tr + td1);
}
// I removed this line. "out" is never defined. I do not know its purpose.
//document.getElementById("id01").innerHTML = out;
}
这是一个有效的 jsfiddle .
关于javascript - 读取 JSON 并输出到 HTML 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31938487/