如何在Javascript中将JSON对象与字符串进行比较

时间:2013-04-28 23:04:13

标签: javascript json string object equals

我正在为http://myttc.ca开发此网站布局。我成功地检索了大部分数据并将其显示在页面上。

但是当我不得不过滤我的搜索以找到只有Subways的停止名称时,我会遇到错误。这是JSON页面http://myttc.ca/finch_station.json。在这里,当我尝试仅访问路径名为Yonge-University-Spadina Subway的站点时,我收到错误Uncaught TypeError: Cannot call method 'equals' of undefined。我也试过简单地放===运算符。也许我必须反序列化或者其他什么,但是现在在整个互联网上解决这个问题后完全无助。我是javaScript的新手,我想也许我在这里遗漏了一些东西。到目前为止,这是我的代码:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
      $(document).ready(function(){
        // retrieving the data.
        $.getJSON("http://myttc.ca/finch_station.json?callback=?", function(data){
          //Storing the string in variable.   
          var subway="Yonge-University-Spadina Subway";

          console.log(data);
          //Displaying the station name first in a div called "stations" in the body.
          $("#stations").append('Station: ' + data.name + '<br/>');

          //Iterating through the stops array to display each stop name 
          $.each(data.stops, function(i,stopz){

          $("#stations").append('&nbsp;&nbsp;Stop: ' + stopz.name + '<br/>');
          //This is my problem area.Not able to compare the routes.name to the string.   
          if(stopz.routes.name === subway) {
            $.each(stopz.routes, function(i,routez) {
              //Displaying the Departure time and shape of the stops.
              $.each(routez.stop_times, function(i,timez) {
                $("#stations").append('&nbsp;&nbsp;&nbsp;&nbsp;Departure-time: ' + timez.departure_time + ' || Shape: ' + timez.shape + '<br/>');  
              });
            });
            }
          });
         });
       });
     </script>

 </head>
 <body>

 <div id="stations">
 </div>
 </body>
 </html>

感谢。

1 个答案:

答案 0 :(得分:1)

考虑到停止数据格式的格式:

{"routes":[],"name":"Finch Station GO Hallway","uri":"finch_station_go_hallway","agency":"Toronto Transit Commission"}

您对stopz.routes.name的引用无效。我认为你的意思是stopz.name。所以你的代码应该是这样的:

            if(stopz.name === subway)
            {
                $.each(stopz.routes, function(i,routez){
                    // ... etc ...
                });
            }
相关问题