解析JSON数据并打印出来

时间:2013-08-17 08:22:28

标签: javascript json

我正在学习JavaScript,我需要从url(http://example.com?index=goog,dji)读取数据,这将返回下面的字符串。现在我想在html表中打印名称和值

[ 
  { "id": "983582" ,"t" : ".DJI" ,"e" : "INDEXDJX" ,"l" : "15,081.47" ,"l_cur" : "15,081.47" ,"s": "0" ,"ltt":"4:35PM EDT" ,"lt" : "Aug 16, 4:35PM EDT" ,"c" : "-30.72" ,"cp" : "-0.20" ,"ccol" : "chr" },
  { "id": "694653" ,"t" : "GOOG" ,"e" : "NASDAQ" ,"l" : "856.91" ,"l_cur" : "856.91" ,"s": "0" ,"ltt":"4:00PM EDT" ,"lt" : "Aug 16, 4:00PM EDT" ,"c" : "-2.75" ,"cp" : "-0.32" ,"ccol" : "chr" }
]

输出

INDEXDJX  - 15,081.47
GOOG - 856.91

我怎样才能使用JavaScript和HTML?

3 个答案:

答案 0 :(得分:2)

尝试Jquery它比纯JavaScript更容易,因为它只需要几行代码 而且jquery也是一个javascript框架

您可以通过在头部添加jquery库来实现它,如下所示

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

脚本标记

下的以下代码
$.ajax({ 
    type: 'GET', 
    url: 'http://example.com?index=goog,dji', 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            $('body').append($('<div>', {
                text: element.name
            }));
        });
    }
});

更新

更准确地说,在您的情况下,此代码将正常工作

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
                $.getJSON('http://example.com?index=goog,dji',function(data){
                    $('body').empty();
                    var html ='<table>';
                    $.each(data, function(entryIndex, entry){
                        $.each(entry, function(entrydataIndex, entrydata){
                            html += '<tr>';                   
                            html += '<strong>'+entrydataIndex+'</strong>'+'-'+ entrydata+'<br/>';               
                            html += '</tr">';                                       
                        });
                    });
                    html += "</table>";
                    $('body').append(html);                       
                });
                return false;

        });
</script>
</head>

<body>
</body>
</html>

答案 1 :(得分:2)

纯javascript示例,虽然使用jQuery,如Sam的回答中提到的,更容易

function loadJSON() {    
    var ajaxRequest;  
    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    }catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
                    //IF YOU ARE NOT ABLE TO REMOVE THE // FROM THE BEGINING OF 
                    //THE JSON DATA THEN YOU WILL NEED TO REMOVE IT BEFORE
                    //PARSING
                    var json = ajaxRequest.responseText".replace(/^\/\/\s/,"");

            //Parse json to an object
            var dataObj = JSON.parse(json);

            //Now you can access the array of objects
            console.log( dataObj[0].INDEXDJX );
            console.log( dataObj[1].GOOG );
        }
    }


    ajaxRequest.open("GET", "http://example.com?index=goog,dji", true);
    ajaxRequest.send(null); 
}

答案 2 :(得分:0)

你可以使用ajax,我将使用jquery更短的代码 p.s:“你正在使用谷歌股票,请注意它距离真实市场晚了15分钟”

<html>
<head>
<title></title>
<meta charset="utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$("document").ready(function(){
 $.ajax({url:'http://example.com?index=goog,dji',dataType: 'json',success:function(data){
      var result="";
      $.each(data,function(index,stock){
          result+= stock.e+" - "+stock.l_cur+"<br/>";
      });
      $("body").append("<div>"+result+"</div>");
}});
});
</script>
</head>
<body>
Results:<br/>
</body>
</html>