如何在Json对象中移动Json数组?

时间:2017-08-01 19:37:05

标签: javascript json

我包含以下返回的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;和标签。

2 个答案:

答案 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
 }

所以你只需要使用cc.textc.confidence

&#13;
&#13;
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;
&#13;
&#13;