我正在对JSON对象进行迭代
我的JSON结构类似于
{"someinfo":{"Parameter":}"ABC":"123","xyz":"456"}}
for (var tempVal in jsonObj.someinfo.Parameter) {
//print tempval
}
当填充JSON中的"Parameter"时,上面的循环将返回正确的值。
如果为空,则会打印arg
JSON中的空"参数"看起来像:
{"someinfo":{"Parameter":"}}
为了在空或非空时打印正确的值,是否有任何方法可以用于循环
填充的Parameter
是object
空的Parameter
是string
var jsonObj1={"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}};
var jsonObj2={"someinfo":{"Parameter":""}};
alert("Full: "+typeof jsonObj1.someinfo.Parameter+" ---- Empty: "+typeof jsonObj2.someinfo.Parameter)
你不能"在字符串中循环",所以如果你改变你的JSON或者像这个一样测试它
if (typeof jsonObj1.someinfo.Parameter==="object") {
for (var tempVal in jsonObj.someinfo.Parameter) {
//print tempval
}
} else {
//empty
}
您可以检查jsonObj.someinfo.Parameter
是否是这样的对象:
var json = {"someinfo":{"Parameter":{"ABC":"123","xyz":"456"}}};
if(typeof json.someinfo.Parameter === "object") {
for(var key in json.someinfo.Parameter) {
// print key
}
} else {
// Do something when it is not an object (empty)
}