我包含以下返回的JSON:
"description": {
"tags": [
"person",
"indoor",
"clothing",
"woman",
"posing",
"hair",
"wearing",
"young",
"holding",
"white",
"shirt",
"smiling",
"black",
"camera",
"red",
"sitting",
"standing",
"yellow",
"blue",
"room"
],
"captions": [
{
"text": "Angelina Jolie wearing a white shirt and black hair",
"confidence": 0.8567016879020947
}
]
},
我已经尝试过多种方式,包括下面这个,我没有得到任何结果:
function gerarLegenda(obj){
for(c in obj.description.captions){
document.getElementById("legenda-collection").innerHTML += '<a href="#!" class="collection-item"><span class="badge red white-text">'+ obj.description[c].captions[c].confidence +" %"+'</span> <span class="new badge red"></span>'+ obj.description[c].captions[c].text +'</a>';
}
}
我这样做是为了显示单独的&#34;字幕&#34;和标签。
答案 0 :(得分:1)
obj.description[c].captions[c].confidence
应为obj.description.captions[c].confidence
修改强> 这可能更容易阅读
function gerarLegenda(obj) {
var legend = document.getElementById("legenda-collection");
obj.description.captions.forEach(function(caption) {
legend.innerHTML += '<a href="#!" class="collection-item"><span class="badge red white-text">'+ caption.confidence +" %"+'</span> <span class="new badge red"></span>'+ caption.text +'</a>';
});
}
请注意,您的此代码会导致layout thrashing,尤其是captions
数组很大时。而是建立一个锚标记字符串,然后写一次到您选择的HTML元素。
答案 1 :(得分:-1)
在for (c in obj.description.captions)
的上下文中,c
已经是这样的对象:
{
"text": "Angelina Jolie wearing a white shirt and black hair",
"confidence": 0.8567016879020947
}
所以你只需要使用c
。 c.text
和c.confidence
。
function gerarLegenda(obj){
for(c in obj.description.captions){
document.getElementById("legenda-collection").innerHTML += '<a href="#!" class="collection-item"><span class="badge red white-text">' + c.confidence +" %"+'</span> <span class="new badge red"></span>'+ c.text +'</a>';
}
}
&#13;