JSON 解析

Object.keys(val)javascript

json 數據以下html

[
{"id":0,"imageLink":"/images/funny-cat.jpg",
    "codeNames":["Juggernaut","Mrs. Wallace","Buttercup"]},
{"id":1,"imageLink":"/images/grumpy-cat.jpg",
    "codeNames":["Oscar","Scrooge","Tyrion"]},
{"id":2,"imageLink":"/images/mischievous-cat.jpg",
    "codeNames":["The Doctor","Loki","Joker"]}
]

.forEach() 函數來循環遍歷JSON數據寫到htmll變量中。  java

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
   </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>

<script>
  $(document).ready(function() {
    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {
      var html = "";
      json.forEach(function(val) {
        var keys = Object.keys(val);
        html += "<div class = 'cat'>";
        keys.forEach(function(key) {
          html += "<b>" + key + "</b>: " + val[key] + "<br>";
        });
        html += "</div><br>";
      });
        $(".message").html(html);

      });
    });
  });
</script>

咱們把其中 "id" 鍵的值爲1的圖片過濾掉。json

json = json.filter(function(val) {
  return (val.id !== 1);
});

json 遍歷函數

var jsonData = { a:12, b:23 };
	
for(var item in jsonData){
 console.info(item);
 console.info(jsonData[item]);
}
相關文章
相關標籤/搜索