我有一个看起来像这个
的API调用返回的json字符串{"study":{"moleculeDescription":"RONTALIZUMAB","protocolTitle":"IMM","protocolNumber":"GA00806","studyName":"Interferon alpha in SLE Phase II LCM Option","therapeuticArea":"INFLAMMATORY,AUTOIMMUNE&BONE","startDate":"2009-03-25","endDate":"2013-08-22"}}
我希望能够使用下面的内容循环浏览json字符串,并将值分配给页面上的输入字段。
function doStuff() {
var myTest = document.getElementById('{!$Component.jsonStr}');
for( k in myTest ){
document.getElementById(k).value = myTest[k];
}
}
然而,只有当我的json字符串(var myTest)看起来像这样时才会起作用(见下文,没有外部{" study":}参数)
{"moleculeDescription":"RONTALIZUMAB","protocolTitle":"IMM","protocolNumber":"GA00806","studyName":"Interferon alpha in SLE Phase II LCM Option","therapeuticArea":"INFLAMMATORY,AUTOIMMUNE&BONE","startDate":"2009-03-25","endDate":"2013-08-22"}
有谁知道如何消除我的json字符串的外部部分,以便我可以使用内部部分?或者有更好的方法,比如修改for语句?感谢您的帮助,如果这是一个愚蠢的问题,对不起,我是个新手。
答案 0 :(得分:1)
var x = {"study":{"moleculeDescription":"RONTALIZUMAB","protocolTitle":"IMM","protocolNumber":"GA00806","studyName":"Interferon alpha in SLE Phase II LCM Option","therapeuticArea":"INFLAMMATORY,AUTOIMMUNE&BONE","startDate":"2009-03-25","endDate":"2013-08-22"}};
var y = x.study;
y 将是必需的var
最好的办法是
for( k in myTest.study )
{
document.getElementById(k).value = myTest[k];
}
答案 1 :(得分:0)
您可以执行以下操作
for (var key in myTest) {
if (myTest.hasOwnProperty(key)) {
var localSet = myTest[key];
// .. here goes your code to iterate through inner object
}
}